如何创建MySQL5的视图
2011-06-11 19:43
337 查看
基本语法:
CREATE [OR REPLACE] [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
VIEW
AS
This statement creates a new view, or replaces an existing one if the
This statement requires the
A view belongs to a database. By default, a new view is created in the current database. To create the view explicitly in a given database, specify the name as
mysql>
Tables and views share the same namespace within a database, so a database cannot contain a table and a view that have the same name.
Views must have unique column names with no duplicates, just like base tables. By default, the names of the columns retrieved by the
Columns retrieved by the
Unqualified table or view names in the
A view can be created from many kinds of
mysql>
| qty | price | value |
+------+-------+-------+
| 3 | 50 | 150 |
+------+-------+-------+
A view definition is subject to the following restrictions:
The
The
The
Within a stored routine, the definition cannot refer to routine parameters or local variables.
Any table or view referred to in the definition must exist. However, after a view has been created, it is possible to drop a table or view that the definition refers to. To check a view definition for problems of this kind, use the
The definition cannot refer to a
The tables named in the view definition must already exist.
You cannot associate a trigger with a view.
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
If you create a view and then change the query processing environment by changing system variables, that may affect the results you get from the view:
mysql>
mysql>
mysql>
| CHARSET(CHAR(65)) | COLLATION(CHAR(65)) |
+-------------------+---------------------+
| latin1 | latin1_swedish_ci |
+-------------------+---------------------+
1 row in set (0.00 sec)
mysql>
mysql>
| CHARSET(CHAR(65)) | COLLATION(CHAR(65)) |
+-------------------+---------------------+
| utf8 | utf8_general_ci |
+-------------------+---------------------+
1 row in set (0.00 sec)
The optional
For
For
For
A reason to choose
A view algorithm can be
No
The
As mentioned earlier,
CREATE ALGORITHM = MERGE VIEW v_merge (vc1, vc2) AS
SELECT c1, c2 FROM t WHERE c3 > 100;
Example 1: Suppose that we issue this statement:
SELECT * FROM v_merge;
MySQL handles the statement as follows:
The view
The resulting statement to be executed becomes:
SELECT c1, c2 FROM t WHERE c3 > 100;
Example 2: Suppose that we issue this statement:
SELECT * FROM v_merge WHERE vc1 < 100;
This statement is handled similarly to the previous one, except that
SELECT c1, c2 FROM t WHERE (c3 > 100) AND (c1 < 100);
Effectively, the statement to be executed has a
WHERE (select WHERE) AND (view WHERE)
The
Aggregate functions (
Refers only to literal values (in this case, there is no underlying table)
Some views are updatable. That is, you can use them in statements such as
Aggregate functions (
Subquery in the select list
Join
Non-updatable view in the
A subquery in the
Refers only to literal values (in this case, there is no underlying table to update)
With respect to insertability (being updatable with
There must be no duplicate view column names.
The view must contain all columns in the base table that do not have a default value.
The view columns must be simple column references and not derived columns. A derived column is one that is not a simple column reference but is derived from an expression. These are examples of derived columns:
3.14159
col1 + 3
UPPER(col2)
col3 / col4
(
A view that has a mix of simple column references and derived columns is not insertable, but it can be updatable if you update only those columns that are not derived. Consider this view:
CREATE VIEW v AS SELECT col1, 1 AS col2 FROM t;
This view is not insertable because
UPDATE v SET col1 = 0;
This update is not allowable because it attempts to update a derived column:
UPDATE v SET col2 = 0;
It is sometimes possible for a multiple-table view to be updatable, assuming that it can be processed with the
For a multiple-table updatable view,
The
In a
mysql>
Here the
ql> INSERT INTO v2 VALUES (2);
Query OK, 1 row affected (0.00 sec)
mysql>
The updatability of views may be affected by the value of the
CREATE [OR REPLACE] [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
VIEW
view_name[(
column_list)]
AS
select_statement[WITH [CASCADED | LOCAL] CHECK OPTION]
This statement creates a new view, or replaces an existing one if the
OR REPLACEclause is given. The
select_statementis a
SELECTstatement that provides the definition of the view. The statement can select from base tables or other views.
This statement requires the
CREATE VIEWprivilege for the view, and some privilege for each column selected by the
SELECTstatement. For columns used elsewhere in the
SELECTstatement you must have the
SELECTprivilege. If the
OR REPLACEclause is present, you must also have the
DELETEprivilege for the view.
A view belongs to a database. By default, a new view is created in the current database. To create the view explicitly in a given database, specify the name as
db_name.view_namewhen you create it.
mysql>
CREATE VIEW test.v AS SELECT * FROM t;
Tables and views share the same namespace within a database, so a database cannot contain a table and a view that have the same name.
Views must have unique column names with no duplicates, just like base tables. By default, the names of the columns retrieved by the
SELECTstatement are used for the view column names. To define explicit names for the view columns, the optional
column_listclause can be given as a list of comma-separated identifiers. The number of names in
column_listmust be the same as the number of columns retrieved by the
SELECTstatement.
Columns retrieved by the
SELECTstatement can be simple references to table columns. They can also be expressions that use functions, constant values, operators, and so forth.
Unqualified table or view names in the
SELECTstatement are interpreted with respect to the default database. A view can refer to tables or views in other databases by qualifying the table or view name with the proper database name.
A view can be created from many kinds of
SELECTstatements. It can refer to base tables or other views. It can use joins,
UNION, and subqueries. The
SELECTneed not even refer to any tables. 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:
The
SELECTstatement cannot contain a subquery in the
FROMclause.
The
SELECTstatement cannot refer to system or user variables.
The
SELECTstatement cannot refer to prepared statement parameters.
Within a stored routine, the definition cannot refer to routine parameters or local variables.
Any table or view referred to in the definition must exist. However, after a view has been created, it is possible to drop a table or view that the definition refers to. To check a view definition for problems of this kind, use the
CHECK TABLEstatement.
The definition cannot refer to a
TEMPORARYtable, and you cannot create a
TEMPORARYview.
The tables named in the view definition must already exist.
You cannot associate a trigger with a view.
ORDER BYis allowed in a view definition, but it is ignored if you select from a view using a statement that has its own
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
LIMITclause, and you select from the view using a statement that has its own
LIMITclause, it is undefined which limit applies. This same principle applies to options such as
ALL,
DISTINCT, or
SQL_SMALL_RESULTthat follow the
SELECTkeyword, and to clauses such as
INTO,
FOR UPDATE,
LOCK IN SHARE MODE, and
PROCEDURE.
If you create a view and then change the query processing environment by changing system variables, that may affect the results you get from the view:
mysql>
CREATE VIEW v AS SELECT CHARSET(CHAR(65)), COLLATION(CHAR(65));Query OK, 0 rows affected (0.00 sec)
mysql>
SET NAMES 'latin1';Query OK, 0 rows affected (0.00 sec)
mysql>
SELECT * FROM v;+-------------------+---------------------+
| CHARSET(CHAR(65)) | COLLATION(CHAR(65)) |
+-------------------+---------------------+
| latin1 | latin1_swedish_ci |
+-------------------+---------------------+
1 row in set (0.00 sec)
mysql>
SET NAMES 'utf8';Query OK, 0 rows affected (0.00 sec)
mysql>
SELECT * FROM v;+-------------------+---------------------+
| CHARSET(CHAR(65)) | COLLATION(CHAR(65)) |
+-------------------+---------------------+
| utf8 | utf8_general_ci |
+-------------------+---------------------+
1 row in set (0.00 sec)
The optional
ALGORITHMclause is a MySQL extension to standard SQL.
ALGORITHMtakes three values:
MERGE,
TEMPTABLE, or
UNDEFINED. The default algorithm is
UNDEFINEDif no
ALGORITHMclause is present. The algorithm affects how MySQL processes the view.
For
MERGE, the text of a statement that refers to the view and the view definition are merged such that parts of the view definition replace corresponding parts of the statement.
For
TEMPTABLE, the results from the view are retrieved into a temporary table, which then is used to execute the statement.
For
UNDEFINED, MySQL chooses which algorithm to use. It prefers
MERGEover
TEMPTABLEif possible, because
MERGEis usually more efficient and because a view cannot be updatable if a temporary table is used.
A reason to choose
TEMPTABLEexplicitly is that locks can be released on underlying tables after the temporary table has been created and before it is used to finish processing the statement. This might result in quicker lock release than the
MERGEalgorithm so that other clients that use the view are not blocked as long.
A view algorithm can be
UNDEFINEDthree ways:
No
ALGORITHMclause is present in the
CREATE VIEWstatement.
The
CREATE VIEWstatement has an explicit
ALGORITHM = UNDEFINEDclause.
ALGORITHM = MERGEis specified for a view that can be processed only with a temporary table. In this case, MySQL generates a warning and sets the algorithm to
UNDEFINED.
As mentioned earlier,
MERGEis handled by merging corresponding parts of a view definition into the statement that refers to the view. The following examples briefly illustrate how the
MERGEalgorithm works. The examples assume that there is a view
v_mergethat has this definition:
CREATE ALGORITHM = MERGE VIEW v_merge (vc1, vc2) AS
SELECT c1, c2 FROM t WHERE c3 > 100;
Example 1: Suppose that we issue this statement:
SELECT * FROM v_merge;
MySQL handles the statement as follows:
v_mergebecomes
t
*becomes
vc1, vc2, which corresponds to
c1, c2
The view
WHEREclause is added
The resulting statement to be executed becomes:
SELECT c1, c2 FROM t WHERE c3 > 100;
Example 2: Suppose that we issue this statement:
SELECT * FROM v_merge WHERE vc1 < 100;
This statement is handled similarly to the previous one, except that
vc1 < 100becomes
c1 < 100and the view
WHEREclause is added to the statement
WHEREclause using an
ANDconnective (and parentheses are added to make sure the parts of the clause are executed with correct precedence). The resulting statement to be executed becomes:
SELECT c1, c2 FROM t WHERE (c3 > 100) AND (c1 < 100);
Effectively, the statement to be executed has a
WHEREclause of this form:
WHERE (select WHERE) AND (view WHERE)
The
MERGEalgorithm requires a one-to relationship between the rows in the view and the rows in the underlying table. If this relationship does not hold, a temporary table must be used instead. Lack of a one-to-one relationship occurs if the view contains any of a number of constructs:
Aggregate functions (
SUM(),
MIN(),
MAX(),
COUNT(), and so forth)
DISTINCT
GROUP BY
HAVING
UNIONor
UNION ALL
Refers only to literal values (in this case, there is no underlying table)
Some views are updatable. That is, you can use them in statements such as
UPDATE,
DELETE, or
INSERTto update the contents of the underlying table. For a view to be updatable, there must be a one-to relationship between the rows in the view and the rows in the underlying table. There are also certain other constructs that make a view non-updatable. To be more specific, a view is not updatable if it contains any of the following:
Aggregate functions (
SUM(),
MIN(),
MAX(),
COUNT(), and so forth)
DISTINCT
GROUP BY
HAVING
UNIONor
UNION ALL
Subquery in the select list
Join
Non-updatable view in the
FROMclause
A subquery in the
WHEREclause that refers to a table in the
FROMclause
Refers only to literal values (in this case, there is no underlying table to update)
ALGORITHM = TEMPTABLE(use of a temporary table always makes a view non-updatable)
With respect to insertability (being updatable with
INSERTstatements), an updatable view is insertable if it also satisfies these additional requirements for the view columns:
There must be no duplicate view column names.
The view must contain all columns in the base table that do not have a default value.
The view columns must be simple column references and not derived columns. A derived column is one that is not a simple column reference but is derived from an expression. These are examples of derived columns:
3.14159
col1 + 3
UPPER(col2)
col3 / col4
(
subquery)
A view that has a mix of simple column references and derived columns is not insertable, but it can be updatable if you update only those columns that are not derived. Consider this view:
CREATE VIEW v AS SELECT col1, 1 AS col2 FROM t;
This view is not insertable because
col2is derived from an expression. But it is updatable if the update does not try to update
col2. This update is allowable:
UPDATE v SET col1 = 0;
This update is not allowable because it attempts to update a derived column:
UPDATE v SET col2 = 0;
It is sometimes possible for a multiple-table view to be updatable, assuming that it can be processed with the
MERGEalgorithm. For this to work, the view must use an inner join (not an outer join or a
UNION). Also, only a single table in the view definition can be updated, so the
SETclause must name only columns from one of the tables in the view. Views that use
UNION ALLare disallowed even though they might be theoretically updatable, because the implementation uses temporary tables to process them.
For a multiple-table updatable view,
INSERTcan work if it inserts into a single table.
DELETEis not supported.
The
WITH CHECK OPTIONclause can be given for an updatable view to prevent inserts or updates to rows except those for which the
WHEREclause in the
select_statementis true.
In a
WITH CHECK OPTIONclause for an updatable view, the
LOCALand
CASCADEDkeywords determine the scope of check testing when the view is defined in terms of another view.
LOCALkeyword restricts the
CHECK OPTIONonly to the view being defined.
CASCADEDcauses the checks for underlying views to be evaluated as well. When neither keyword is given, the default is
CASCADED. Consider the definitions for the following table and set of views:
mysql>
CREATE TABLE t1 (a INT);mysql>
CREATE VIEW v1 AS SELECT * FROM t1 WHERE a < 2->
WITH CHECK OPTION;mysql>
CREATE VIEW v2 AS SELECT * FROM v1 WHERE a > 0->
WITH LOCAL CHECK OPTION;mysql>
CREATE VIEW v3 AS SELECT * FROM v1 WHERE a > 0->
WITH CASCADED CHECK OPTION;
Here the
v2and
v3views are defined in terms of another view,
v1.
v2has a
LOCALcheck option, so inserts are tested only against the
v2check.
v3has a
CASCADEDcheck option, so inserts are tested not only against its own check, but against those of underlying views. The following statements illustrate these differences:
ql> INSERT INTO v2 VALUES (2);
Query OK, 1 row affected (0.00 sec)
mysql>
INSERT INTO v3 VALUES (2);ERROR 1369 (HY000): CHECK OPTION failed 'test.v3'
The updatability of views may be affected by the value of the
updatable_views_with_limitsystem variable. (完)
相关文章推荐
- 如何创建MySQL5的视图
- 如何创建物化视图
- 如何在MFC单文档中创建多视图
- [PHP]在CodeIgniter中如何利用CSS创建视图
- 如何创建可扩展表视图中的iOS 学习和拓展优化(有待更新)
- mysql中的存储过程、触发器、视图是如何创建的,以及PHP中是如何调用的
- 详细讲解如何在MFC单/多文档中创建多视图(具体代码)
- Oracle、MySQL如何创建视图
- android2.3 View视图框架源码分析之一:android是如何创建一个view的?
- C++--如何实现SDI程序使用CSplitterWnd创建的多个视图的动态地显示和关闭视图
- sql如何创建视图
- 视图控制器父类是使用Xib创建的,子类如何继承父类的样式
- 在Oracle中如何创建带参数的视图?
- 如何创建可扩展表视图中的iOS 学习和拓展优化(有待更新)
- View视图框架源码分析之一:android是如何创建一个view
- android2.3 View视图框架源码分析之一:android是如何创建一个view的?
- 如何在MySql中创建视图?
- 如何在navicat for MySQL 创建视图
- sqlserver数据库创建视图时如何改变字段类型以及查询视图详细内容
- 如何在navicat创建视图