VIEW [db_name.]view_name [(column_list)]
AS select_statement
[WITH [CASCADED | LOCAL] CHECK OPTION]
通过该语句可以创建视图,若给定了[OR REPLACE],则表示当已具有同名的视图时,将覆盖原视图。select_statement是一个查询语句,这个查询语句可从表或其它的视图中查询。视图属于数据库,因此需要指定数据库的名称,若未指定时,表示在当前的数据库创建新视图。
表和数据库共享数据库中相同的名称空间,因此,数据库不能包含相同名称的表和视图,并且,视图的列名也不能重复。
Eg. 本例创建一个产品表(product)和一个购买记录表(purchase),再通过视图purchase_detail查询出购买的详细信息。
CREATE TABLE product
(
);
INSERT INTO product VALUES(1, 'apple ', 5.5);
CREATE TABLE purchase
(
);
INSERT INTO purchase VALUES(1, 1, 10, NOW());
CREATE VIEW purchase_detail AS SELECT product.name as name, product .price as price, purchase.qty as qty, product .price * purchase.qty as total_value from product, purchase where product.product_id = purchase.product_id;
创建成功后,输入:SELECT * FROM purchase_detail;
运行效果如下:
+-------+-------+-----+-------------+
| name
+-------+-------+-----+-------------+
| apple |
+-------+-------+-----+-------------+
1 row in set (0.01 sec)
创建视图存在如下注意事项:
(1)
(2)
(3)
(4)
(5)
(6)
(7)
(8)
(9)
(10)
5. 修改视图——ALTER VIEW
ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
VIEW view_name [(column_list)]
AS select_statement
[WITH [CASCADED | LOCAL] CHECK OPTION]
该语句用于更改已有视图的定义。其语法与CREATE VIEW类似。
Eg. 将上一小节中中创建的视purchase_detail进行修改,去掉qty列,语句如下:
ALTER VIEW purchase_detail AS SELECT product.name as name, product .price as price, product .price * purchase.qty as total_value from product, purchase where product.product_id = purchase.product_id;
此时通过语句:select * from purchase_detail;对视图进行查询时,结果如下:
+-------+-------+-------------+
| name
+-------+-------+-------------+
| apple |
+-------+-------+-------------+
修改视图的注意事项除了第一条外跟创建视图的注意事项是一样的。第(1)条应改为:
该语句需要具有针对视图的CREATE VIEW和DROP权限,也需要针对SELECT语句中引用的每一列的某些权限。
6. 删除视图——DROP VIEW
DROP VIEW [IF EXISTS]
view_name [, view_name] ...
[RESTRICT | CASCADE]
该语句用户删除视图,可一次删除多个视图。[IF EXISTS]选项确保语句正确运行。若没有该子句,当指定的视图不存在时,将发生错误。
Eg1. 删除视图purchase_detail:DROP VIEW purchase_detail;
Eg2. 删除一个未知的视图:DROP VIEW IF EXISTS test_view;
Eg3. 删除多个视图:DROP VIEW IF EXISTS test_view1, test_view2;
注意事项
必须对要删除的一个或多个视图拥有DROP VIEW的权限。
7.查看视图 -- SHOW CREATE VIEW
mysql> SHOW CREATE VIEW v;
+------+----------------------------------------------------+
| View | Create View |
+------+----------------------------------------------------+
| v | CREATE VIEW `test`.`v` AS select 1 AS `a`,2 AS `b` |
+------+----------------------------------------------------+