CREATE VIEW

The CREATE VIEW statement saves a SELECT statement as a queryable object, similar to a table. Views in TiDB are non-materialized. This means that as a view is queried, TiDB will internally rewrite the query to combine the view definition with the SQL query.

Synopsis

CreateViewStmt

CREATE VIEW - 图1

OrReplace

CREATE VIEW - 图2

ViewAlgorithm

CREATE VIEW - 图3

ViewDefiner

CREATE VIEW - 图4

ViewSQLSecurity

CREATE VIEW - 图5

ViewName

CREATE VIEW - 图6

ViewFieldList

CREATE VIEW - 图7

ViewCheckOption

CREATE VIEW - 图8

  1. CreateViewStmt ::=
  2. 'CREATE' OrReplace ViewAlgorithm ViewDefiner ViewSQLSecurity 'VIEW' ViewName ViewFieldList 'AS' CreateViewSelectOpt ViewCheckOption
  3. OrReplace ::=
  4. ( 'OR' 'REPLACE' )?
  5. ViewAlgorithm ::=
  6. ( 'ALGORITHM' '=' ( 'UNDEFINED' | 'MERGE' | 'TEMPTABLE' ) )?
  7. ViewDefiner ::=
  8. ( 'DEFINER' '=' Username )?
  9. ViewSQLSecurity ::=
  10. ( 'SQL' 'SECURITY' ( 'DEFINER' | 'INVOKER' ) )?
  11. ViewName ::= TableName
  12. ViewFieldList ::=
  13. ( '(' Identifier ( ',' Identifier )* ')' )?
  14. ViewCheckOption ::=
  15. ( 'WITH' ( 'CASCADED' | 'LOCAL' ) 'CHECK' 'OPTION' )?

Examples

  1. mysql> CREATE TABLE t1 (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, c1 INT NOT NULL);
  2. Query OK, 0 rows affected (0.11 sec)
  3. mysql> INSERT INTO t1 (c1) VALUES (1),(2),(3),(4),(5);
  4. Query OK, 5 rows affected (0.03 sec)
  5. Records: 5 Duplicates: 0 Warnings: 0
  6. mysql> CREATE VIEW v1 AS SELECT * FROM t1 WHERE c1 > 2;
  7. Query OK, 0 rows affected (0.11 sec)
  8. mysql> SELECT * FROM t1;
  9. +----+----+
  10. | id | c1 |
  11. +----+----+
  12. | 1 | 1 |
  13. | 2 | 2 |
  14. | 3 | 3 |
  15. | 4 | 4 |
  16. | 5 | 5 |
  17. +----+----+
  18. 5 rows in set (0.00 sec)
  19. mysql> SELECT * FROM v1;
  20. +----+----+
  21. | id | c1 |
  22. +----+----+
  23. | 3 | 3 |
  24. | 4 | 4 |
  25. | 5 | 5 |
  26. +----+----+
  27. 3 rows in set (0.00 sec)
  28. mysql> INSERT INTO t1 (c1) VALUES (6);
  29. Query OK, 1 row affected (0.01 sec)
  30. mysql> SELECT * FROM v1;
  31. +----+----+
  32. | id | c1 |
  33. +----+----+
  34. | 3 | 3 |
  35. | 4 | 4 |
  36. | 5 | 5 |
  37. | 6 | 6 |
  38. +----+----+
  39. 4 rows in set (0.00 sec)
  40. mysql> INSERT INTO v1 (c1) VALUES (7);
  41. ERROR 1105 (HY000): insert into view v1 is not supported now.

MySQL compatibility

  • Currently, any view in TiDB cannot be inserted or updated (that is, INSERT VIEW and UPDATE VIEW are not supported). WITH CHECK OPTION is only syntactically compatible but does not take effect.
  • Currently, the view in TiDB does not support ALTER VIEW, but you can use CREATE OR REPLACE instead.
  • Currently, the ALGORITHM field is only syntactically compatible in TiDB but does not take effect. TiDB currently only supports the MERGE algorithm.

See also