视图(view)是一种虚拟存在的表。视图并不在数据库中实际存在,行和列数据来自定义视图的查询中使用的表,并且是在使用视图时动态生成的。通俗的讲,视图就是一条select语句执行后返回的结果集。所以我们在创建视图的时候,主要的工作就落在创建这条SQL查询语句上。
视图与普通表的优势 | --- |
---|---|
简单 | 使用视图的用户完全不需要关心后面对应的表的结构,关联条件和筛选条件,对用户来说已经是过滤好的复合条件的结果集。 |
安全 | 使用视图的用户只能访问他们被允许查询的结果集,对表的权限管理并不能限制到某个行某个列,但是通过视图就可以简单的实现。 |
数据独立 | 一旦视图的结构确定了,可以屏蔽表结构变化对用户的影响,源表增加列对视图没有影响;源表修改列名,则可以通过修改视图来解决,不会造成对访问者的影响。 |
创建
create [or replace] [algorithm = {undefined|merge|temptable}]
view view_name [(column_list)]
as select_statement
[with [cascaded|local] check option]
#选项
#with [cascaded|local] check option] 决定了是否允许更新数据记录不再满足视图的条件。
# local: 只要满足本视图的条件就可以更新
# cascaded: 必须满足所有针对该视图的所有视图条件才可以更新,默认值。
####实例(建表语句参考[mysql 索引](https://www.linuxsre.cn/wiki/dbserver/186 "mysql 索引"))
create view view_city_country as select c.*,t.country_name from city c,country t where c.country_id = t.country_id;
#查询
mysql> select * from view_city_country;
+---------+-----------+------------+--------------+
| city_id | city_name | country_id | country_name |
+---------+-----------+------------+--------------+
| 1 | 西安 | 1 | china |
| 2 | NewYork | 2 | America |
| 3 | 北京 | 1 | china |
| 4 | 上海 | 1 | china |
+---------+-----------+------------+--------------+
4 rows in set (0.04 sec)
#更新视图
update view_city_country set name='西安市' where city_id=1;
修改视图
alter [algorithm = {undefined|merge|temptable}]
view view_name [(column_list)]
as select select_statement
[with [cascaded|local] check option]
查看视图 show tables; 包含了视图和表
mysql> show tables;
+-------------------+
| Tables_in_demo_01 |
+-------------------+
| city |
| country |
| view_city_country |
+-------------------+
3 rows in set (0.07 sec)
####查看视图的创建语句show create view
mysql> show create view view_city_country\G
*************************** 1. row ***************************
View: view_city_country
Create View: CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `view_city_country` AS select `c`.`city_id` AS `city_id`,`c`.`city_name` AS `city_name`,`c`.`country_id` AS `country_id`,`t`.`country_name` AS `country_name` from (`city` `c` join `country` `t`) where (`c`.`country_id` = `t`.`country_id`)
character_set_client: utf8mb4
collation_connection: utf8mb4_0900_ai_ci
1 row in set (0.00 sec)
删除视图
drop view [if exists] view_name [,view_name] ...[restrict|cascade]
###示例:
mysql> drop view view_city_country;
Query OK, 0 rows affected (0.25 sec)