视图是一张虚拟表,是从一个或多个表中导出的表,其数据其实存储在其引用的表中,本身并没有实际的数据。删除和创建视图,对其引用的表没有什么影响。
1. 创建视图
CREATE VIEW <视图名> AS <SELECT语句>
e.g.
# 不写字段名,则默认使用引用的表中的字段名
mysql> create view vuser as select * from user; Query OK, 0 rows affected (0.02 sec) mysql> select * from vuser; +----+------+----------+---------+------+ | id | name | password | balance | debt | +----+------+----------+---------+------+ | 1 | Wang | 1234 | 15000 | 0 | | 2 | song | 1234 | 3000 | 100 | | 3 | li | 1234 | 2000 | 0 | | 4 | zhao | NULL | NULL | NULL | | 5 | qian | NULL | NULL | NULL | | 6 | sun | NULL | NULL | NULL | | 7 | Zhou | NULL | NULL | 90 | | 10 | Wang | NULL | 15000 | NULL | +----+------+----------+---------+------+
# 自定义字段名
mysql> create view v_user -> (vid,vname,vbalance) -> as select id,name,balance from user; Query OK, 0 rows affected (0.01 sec) mysql> select * from v_user; +-----+-------+----------+ | vid | vname | vbalance | +-----+-------+----------+ | 1 | Wang | 15000 | | 2 | song | 3000 | | 3 | li | 2000 | | 4 | zhao | NULL | | 5 | qian | NULL | | 6 | sun | NULL | | 7 | Zhou | NULL | | 10 | Wang | 15000 | +-----+-------+----------+
2. 修改视图
其实就是更新select的部分
ALTER VIEW <视图名> AS <SELECT语句>
或者可以删除视图,然后重新创建
3. 删除视图:
DROP VIEW <视图名1> [ , <视图名2> …]
# 带判断的删除
DROP VIEW IF EXISTS v_students_info;