Create a View
suggest changePrivileges
CREATE VIEW requires the CREATE VIEW privilege, plus some privilege for each column selected. For columns used elsewhere in the SELECT, you need the SELECT privilege. OR REPLACE also requires DROP on the view. If the definer is not the current user, you also need the SET_USER_ID privilege (called SUPER before MySQL 8.0.16).
When a view is referenced, privilege checking occurs.
A view belongs to a database. By default, a new view is created in the current database. To create it in a given database, use a qualified name, for example:
db_name.view_name
CREATE VIEW test.v AS SELECT * FROM t;
Note - Within a database, base tables and views share the same namespace, so a base table and a view cannot have the same name.
A VIEW can:
- be created from many kinds of SELECT statements
- refer to base tables or other views
- use joins, UNION, and subqueries
- The
SELECTneed not refer to any tables
Another Example
The following example defines a view that selects two columns from another table as well as an expression calculated from those columns:
mysql> CREATE TABLE t (qty INT, price INT);
mysql> INSERT INTO t VALUES(3, 50);
mysql> CREATE VIEW v AS SELECT qty, price, qty*price AS value FROM t;
mysql> SELECT * FROM v;
+------+-------+-------+
| qty | price | value |
+------+-------+-------+
| 3 | 50 | 150 |
+------+-------+-------+
Restrictions
-
Before MySQL 5.7.7, the SELECT statement cannot contain a subquery in the FROM clause.
-
The SELECT statement cannot refer to system variables or user-defined variables.
-
Within a stored program, the SELECT statement cannot refer to program parameters or local variables.
-
The SELECT statement cannot refer to prepared statement parameters.
-
Any table or view referred to in the definition must exist. After the view has been created, dropping a table or view it refers to makes later use of the view fail.
CHECK TABLEreports that problem. -
The definition cannot refer to a
TEMPORARYtable, and you cannot create aTEMPORARYview. -
You cannot associate a trigger with a view.
-
Aliases for column names in the
SELECTare checked against the maximum column length of 64 characters, not the maximum alias length of 256 characters. -
A
VIEWmay or may not optimize as well as the equivalentSELECT. It is unlikely to optimize any better.