13.1.23 CREATE VIEW Statement语句

CREATE
    [OR REPLACE]
    [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
    [DEFINER = user]
    [SQL SECURITY { DEFINER | INVOKER }]
    VIEW view_name [(column_list)]
    AS select_statement
    [WITH [CASCADED | LOCAL] CHECK OPTION]

The CREATE VIEW statement creates a new view, or replaces an existing view if the OR REPLACE clause is given. CREATE VIEW语句创建一个新视图,或者在给定OR REPLACE子句的情况下替换现有视图。If the view does not exist, CREATE OR REPLACE VIEW is the same as CREATE VIEW. 如果视图不存在,则CREATE OR REPLACE VIEWCREATE VIEW相同。If the view does exist, CREATE OR REPLACE VIEW replaces it.如果该视图确实存在,CREATE OR REPLACE VIEW将替换该视图。

For information about restrictions on view use, see Section 25.9, “Restrictions on Views”.有关视图使用限制的信息,请参阅第25.9节,“视图限制”

The select_statement is a SELECT statement that provides the definition of the view. select_statement是提供视图定义的SELECT语句。(Selecting from the view selects, in effect, using the SELECT statement.) (从视图中选择实际上是使用SELECT语句进行选择。)The select_statement can select from base tables, other views. select_statement可以从基表、其他视图中进行选择。Beginning with MySQL 8.0.19, the SELECT statement can use a VALUES statement as its source, or can be replaced with a TABLE statement, as with CREATE TABLE ... SELECT.从MySQL 8.0.19开始,SELECT语句可以使用VALUES语句作为其源,也可以替换为TABLE语句,如CREATE TABLE ... SELECT

The view definition is frozen at creation time and is not affected by subsequent changes to the definitions of the underlying tables. 视图定义在创建时被“冻结”,并且不受基础表定义的后续更改的影响。For example, if a view is defined as SELECT * on a table, new columns added to the table later do not become part of the view, and columns dropped from the table result in an error when selecting from the view.例如,如果在表中将视图定义为SELECT *,则以后添加到表中的新列不会成为视图的一部分,并且从表中删除的列在从视图中选择时会导致错误。

The ALGORITHM clause affects how MySQL processes the view. ALGORITHM子句影响MySQL处理视图的方式。The DEFINER and SQL SECURITY clauses specify the security context to be used when checking access privileges at view invocation time. DEFINERSQL SECURITY子句指定在视图调用时检查访问权限时要使用的安全上下文。The WITH CHECK OPTION clause can be given to constrain inserts or updates to rows in tables referenced by the view. These clauses are described later in this section.可以使用WITH CHECK OPTION子句来约束对视图引用的表中的行的插入或更新。本节后面将介绍这些子句。

The CREATE VIEW statement requires the CREATE VIEW privilege for the view, and some privilege for each column selected by the SELECT statement. CREATE VIEW语句需要视图的CREATE VIEW权限,以及SELECT语句所选的每列的一些权限。For columns used elsewhere in the SELECT statement, you must have the SELECT privilege. 对于SELECT语句中其他位置使用的列,必须具有SELECT权限。If the OR REPLACE clause is present, you must also have the DROP privilege for the view. 如果存在OR REPLACE子句,则还必须具有该视图的DROP权限。If the DEFINER clause is present, the privileges required depend on the user value, as discussed in Section 25.6, “Stored Object Access Control”.如果存在DEFINER子句,则所需的权限取决于user值,如第25.6节,“存储对象访问控制”所述。

When a view is referenced, privilege checking occurs as described later in this section.引用视图时,将按照本节后面的说明进行权限检查。

A view belongs to a database. 视图属于数据库。By default, a new view is created in the default database. 默认情况下,将在默认数据库中创建新视图。To create the view explicitly in a given database, use db_name.view_name syntax to qualify the view name with the database name:要在给定数据库中显式创建视图,请使用db_name.view_name语法使用数据库名称限定视图名称:

CREATE VIEW test.v AS SELECT * FROM t;

Unqualified table or view names in the SELECT statement are also interpreted with respect to the default database. SELECT语句中的非限定表名或视图名也将根据默认数据库进行解释。A view can refer to tables or views in other databases by qualifying the table or view name with the appropriate database name.通过使用适当的数据库名称限定表或视图名称,视图可以引用其他数据库中的表或视图。

Within a database, base tables and views share the same namespace, so a base table and a view cannot have the same name.在数据库中,基表和视图共享相同的命名空间,因此基表和视图不能具有相同的名称。

Columns retrieved by the SELECT statement can be simple references to table columns, or expressions that use functions, constant values, operators, and so forth.SELECT语句检索的列可以是对表列的简单引用,也可以是使用函数、常量值、运算符等的表达式。

A view must have unique column names with no duplicates, just like a base table. 一个视图必须有唯一的列名,并且没有重复项,就像一个基表一样。By default, the names of the columns retrieved by the SELECT statement are used for the view column names. 默认情况下,SELECT语句检索的列的名称用于视图列名。To define explicit names for the view columns, specify the optional column_list clause as a list of comma-separated identifiers. 要定义视图列的显式名称,请将可选的column_list子句指定为逗号分隔标识符的列表。The number of names in column_list must be the same as the number of columns retrieved by the SELECT statement.column_list中的名称数必须与SELECT语句检索到的列数相同。

A view can be created from many kinds of SELECT statements. 可以从多种SELECT语句创建视图。It can refer to base tables or other views. 它可以引用基表或其他视图。It can use joins, UNION, and subqueries. 它可以使用联接、UNION和子查询。The SELECT need not even refer to any tables:SELECT甚至不需要引用任何表:

CREATE VIEW v_today (today) AS SELECT CURRENT_DATE;

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 |
+------+-------+-------+

A view definition is subject to the following restrictions:视图定义受以下限制:

ORDER BY is permitted in a view definition, but it is ignored if you select from a view using a statement that has its own ORDER BY.视图定义中允许使用ORDER BY,但如果使用具有自己ORDER BY的语句从视图中选择,则将忽略ORDER BY

For other options or clauses in the definition, they are added to the options or clauses of the statement that references the view, but the effect is undefined. 对于定义中的其他选项或子句,它们将添加到引用视图的语句的选项或子句中,但效果未定义。For example, if a view definition includes a LIMIT clause, and you select from the view using a statement that has its own LIMIT clause, it is undefined which limit applies. 例如,如果视图定义包含LIMIT子句,并且您使用具有自己的LIMIT子句的语句从视图中选择,则未定义应用哪个LIMIT子句。This same principle applies to options such as ALL, DISTINCT, or SQL_SMALL_RESULT that follow the SELECT keyword, and to clauses such as INTO, FOR UPDATE, FOR SHARE, LOCK IN SHARE MODE, and PROCEDURE.同样的原则也适用于SELECT关键字后面的ALLDISTINCTSQL_SMALL_RESULT等选项,以及INTOFOR UPDATEFOR SHARELOCK IN SHARE MODEPROCEDURE等子句。

The results obtained from a view may be affected if you change the query processing environment by changing system variables:如果通过更改系统变量更改查询处理环境,则从视图获得的结果可能会受到影响:

mysql> CREATE VIEW v (mycol) AS SELECT 'abc';
Query OK, 0 rows affected (0.01 sec)

mysql> SET sql_mode = '';
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT "mycol" FROM v;
+-------+
| mycol |
+-------+
| mycol |
+-------+
1 row in set (0.01 sec)

mysql> SET sql_mode = 'ANSI_QUOTES';
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT "mycol" FROM v;
+-------+
| mycol |
+-------+
| abc   |
+-------+
1 row in set (0.00 sec)

The DEFINER and SQL SECURITY clauses determine which MySQL account to use when checking access privileges for the view when a statement is executed that references the view. 当执行引用视图的语句时,DEFINERSQL SECURITY子句确定在检查视图的访问权限时要使用哪个MySQL帐户。The valid SQL SECURITY characteristic values are DEFINER (the default) and INVOKER. 有效的SQL SECURITY特征值是DEFINER(默认值)和INVOKERThese indicate that the required privileges must be held by the user who defined or invoked the view, respectively.这表明所需的权限必须分别由定义或调用视图的用户持有。

If the DEFINER clause is present, the user value should be a MySQL account specified as 'user_name'@'host_name', CURRENT_USER, or CURRENT_USER(). 如果存在DEFINER子句,则用户值应为指定为'user_name'@'host_name'CURRENT_USERCURRENT_USER()的MySQL帐户。The permitted user values depend on the privileges you hold, as discussed in Section 25.6, “Stored Object Access Control”. 允许的user值取决于您拥有的权限,如第25.6节,“存储对象访问控制”所述。Also see that section for additional information about view security.有关视图安全性的更多信息,请参阅该部分。

If the DEFINER clause is omitted, the default definer is the user who executes the CREATE VIEW statement. 如果省略了DEFINER子句,则默认的DEFINER是执行CREATE VIEW语句的用户。This is the same as specifying DEFINER = CURRENT_USER explicitly.这与显式指定DEFINER=CURRENT_USER相同。

Within a view definition, the CURRENT_USER function returns the view's DEFINER value by default. 在视图定义中,默认情况下,CURRENT_USER函数返回视图的DEFINER值。For views defined with the SQL SECURITY INVOKER characteristic, CURRENT_USER returns the account for the view's invoker. 对于使用SQL SECURITY INVOKER特性定义的视图,CURRENT_USER返回视图调用程序的帐户。For information about user auditing within views, see Section 6.2.22, “SQL-Based Account Activity Auditing”.有关视图中用户审核的信息,请参阅第6.2.22节,“基于SQL的帐户活动审核”

Within a stored routine that is defined with the SQL SECURITY DEFINER characteristic, CURRENT_USER returns the routine's DEFINER value. 在使用SQL SECURITY DEFINER特性定义的存储例程中,CURRENT_USER返回例程的定义器值。This also affects a view defined within such a routine, if the view definition contains a DEFINER value of CURRENT_USER.如果视图定义包含CURRENT_USERDEFINER值,则这也会影响在该例程中定义的视图。

MySQL checks view privileges like this:MySQL按如下方式检查查看权限:

Example: A view might depend on a stored function, and that function might invoke other stored routines. 示例:视图可能依赖于存储函数,该函数可能调用其他存储例程。For example, the following view invokes a stored function f():例如,以下视图调用存储函数f()

CREATE VIEW v AS SELECT * FROM t WHERE t.id = f(t.name);

Suppose that f() contains a statement such as this:假设f()包含如下语句:

IF name IS NULL then
  CALL p1();
ELSE
  CALL p2();
END IF;

The privileges required for executing statements within f() need to be checked when f() executes. 执行f()时,需要检查在f()内执行语句所需的权限。This might mean that privileges are needed for p1() or p2(), depending on the execution path within f(). 这可能意味着p1()p2()需要特权,具体取决于f()中的执行路径。Those privileges must be checked at runtime, and the user who must possess the privileges is determined by the SQL SECURITY values of the view v and the function f().必须在运行时检查这些权限,并且必须拥有这些权限的用户由视图v和函数f()SQL SECURITY值决定。

The DEFINER and SQL SECURITY clauses for views are extensions to standard SQL. 视图的DEFINERSQL SECURITY子句是标准SQL的扩展。In standard SQL, views are handled using the rules for SQL SECURITY DEFINER. 在标准SQL中,使用SQL SECURITY DEFINER规则处理视图。The standard says that the definer of the view, which is the same as the owner of the view's schema, gets applicable privileges on the view (for example, SELECT) and may grant them. MySQL has no concept of a schema owner, so MySQL adds a clause to identify the definer. 该标准规定,视图的定义者(与视图模式的所有者相同)可以获得视图的适用权限(例如,SELECT),并可以授予这些权限。MySQL没有模式“所有者”的概念,因此MySQL添加了一个子句来标识定义者。The DEFINER clause is an extension where the intent is to have what the standard has; that is, a permanent record of who defined the view. DEFINER子句是一种延伸,其目的是要达到标准的要求;也就是说,谁定义了视图的永久记录。This is why the default DEFINER value is the account of the view creator.这就是为什么默认DEFINER值是视图创建者的帐户。

The optional ALGORITHM clause is a MySQL extension to standard SQL. It affects how MySQL processes the view. 可选的ALGORITHM子句是标准SQL的MySQL扩展。它影响MySQL处理视图的方式。ALGORITHM takes three values: MERGE, TEMPTABLE, or UNDEFINED. ALGORITHM有三个值:MERGE(合并)、TEMPTABLE(可诱惑)或UNDEFINED(未定义)。For more information, see Section 25.5.2, “View Processing Algorithms”, as well as Section 8.2.2.4, “Optimizing Derived Tables, View References, and Common Table Expressions with Merging or Materialization”.有关更多信息,请参阅第25.5.2节,“视图处理算法”,以及第8.2.2.4节,“通过合并或物化优化派生表、视图引用和公共表表达式”

Some views are updatable. 有些视图是可更新的。That is, you can use them in statements such as UPDATE, DELETE, or INSERT to update the contents of the underlying table. 也就是说,您可以在诸如UPDATEDELETEINSERT之类的语句中使用它们来更新基础表的内容。For a view to be updatable, there must be a one-to-one relationship between the rows in the view and the rows in the underlying table. 要使视图可更新,视图中的行与基础表中的行之间必须存在一对一的关系。There are also certain other constructs that make a view nonupdatable.还有一些其他构造使视图不可更新。

A generated column in a view is considered updatable because it is possible to assign to it. 视图中生成的列被认为是可更新的,因为它可以指定给它。However, if such a column is updated explicitly, the only permitted value is DEFAULT. 但是,如果显式更新此列,则唯一允许的值为DEFAULTFor information about generated columns, see Section 13.1.20.8, “CREATE TABLE and Generated Columns”.有关生成列的信息,请参阅第13.1.20.8节,“创建表和生成列”

The WITH CHECK OPTION clause can be given for an updatable view to prevent inserts or updates to rows except those for which the WHERE clause in the select_statement is true.可以为可更新视图提供WITH CHECK OPTION子句,以防止插入或更新行,select_statementWHERE子句为true的行除外。

In a WITH CHECK OPTION clause for an updatable view, the LOCAL and CASCADED keywords determine the scope of check testing when the view is defined in terms of another view. 在可更新视图的WITH CHECK OPTION子句中,当根据另一个视图定义视图时,LOCAL关键字和CASCADED关键字确定检查测试的范围。The LOCAL keyword restricts the CHECK OPTION only to the view being defined. LOCAL关键字将CHECK OPTION仅限于正在定义的视图。CASCADED causes the checks for underlying views to be evaluated as well. CASCADED也会导致对基础视图的检查进行评估。When neither keyword is given, the default is CASCADED.当两个关键字都没有给出时,默认值是级联的。

For more information about updatable views and the WITH CHECK OPTION clause, see Section 25.5.3, “Updatable and Insertable Views”, and Section 25.5.4, “The View WITH CHECK OPTION Clause”.有关可更新视图和WITH CHECK OPTION子句的更多信息,请参阅第25.5.3节,“可更新和可插入视图”第25.5.4节,“WITH CHECK OPTION子句”