一、含义
mysql5.1版本出现的新特性,本身是一个虚拟表,它的数据来自于表,通过执行时动态生成。
好处:
- 简化了sql语句
- 提高了sql的重用性
- 保护了基表的数据,以高了安全性
二、视图的创建和使用
视图创建语法:
CREATE VIEW 视图名
AS
查询语句;
视图创建和使用案例
#1.查询邮箱中包含a字符的员工名、部门名和工种信息
#①创建
CREATE VIEW myv1
AS
SELECT last_name,department_name,job_title
FROM employees e
JOIN departments d ON e.department_id=d.department_id
JOIN jobs j ON j.job_id=e.job_id;
#②使用
SELECT * FROM myv1 WHERE last_name LIKE '%a%';
#2.查询各部门的平均工资级别
#创建视图查看每个部门的平均工资
CREATE VIEW myv2
AS
SELECT AVG(salary) ag,department_id
FROM employees
GROUP BY department_id;
#②使用
SELECT myv2.ag,g.grade_level
FROM myv2
JOIN job_grades g
ON myv2.ag BETWEEN g.lowest_sal AND g.highest_sal;
#3.查询平均工资最低的部门信息
SELECT * FROM myv2 ORDER BY ag LIMIT 1;
#4.查询平均工资最低的部门名和工资
CREATE VIEW myv3
AS
SELECT * FROM myv2 ORDER BY ag LIMIT 1;
SELECT d.*,m.ag
FROM myv3 m
JOIN departments d
ON m.department_id=d.department_id;
三、视图的修改
方式一:
语法:
CREATE OR REPLACE VIEW 视图名
AS
查询语句;
CREATE OR REPLACE VIEW myv3
AS
SELECT AVG( salary),job_id
FROM employees
GROUP BY job_id;
方式二:
语法:
ALTER VIEW 视图名
AS
查询语句;
ALTER VIEW myv3
AS
SELECT * FROM employees;
四、删除视图
/*
语法:drop view 视图名,视图名,...;
*/
DROP VIEW myv1,myv2,myv3;
五、查看视图
DESC myv2;
SHOW CREATE VIEW myv2;
六、视图的更新
CREATE OR REPLACE VIEW myv1
AS
SELECT last_name,email
FROM employees;
-
插入
INSERT INTO myv1 VALUES('张飞','zf@qq.com' );
-
修改
UPDATE myv1 SET last_name='张无忌' WHERE last_name='张飞';
-
删除
DELETE FROM myv1 WHERE last_name='张无忌';
七、试图不允许更新的情况
- 包含以下关键字的sql语句:分组函数、distinct、group by、having、union或者union all
- 常量视图
- select中包含子查询
- join
- from一个不能更新的视图
- where子句的子查询引用了from子句中的表