基础知识:
含义:虚拟表,和普通表一样使用,mysql5.1版本出现的新特性,是通过表动态生成的数据
比较:
视图create view只是保存了sql逻辑增删改查,只是一般不能增删改
表create table保存了数据增删改查
案例:查询姓张的学生名和专业名
连表查询:
SELECT stuname,majorname
FROM stuinfo s
INNER JOIN major m ON s.`majorid`= m.`id`
WHERE s.`stuname` LIKE '张%';
使用视图:
CREATE VIEW v1
AS
SELECT stuname,majorname
FROM stuinfo s
INNER JOIN major m ON s.`majorid`= m.`id`;
最终结果:SELECT * FROM v1 WHERE stuname LIKE '张%';
一、创建视图
语法:create view 视图名 as 查询语句;
-- 创建视图 -- 查询姓名中包含a字符的员工名、部门名和工种信息 CREATE VIEW lgs1 AS SELECT last_name,department_name,job_title FROM t_mysql_employees e JOIN t_mysql_departments d ON e.department_id = d.department_id JOIN t_mysql_jobs j ON j.job_id = e.job_id; -- 使用 select * from lgs1 WHERE last_name LIKE '%a%';
二、视图的修改
方式一:create or replace view 视图名 as 查询语句;
-- 修改为查询员工名和最大工资 CREATE OR REPLACE VIEW lgs1 AS SELECT AVG(max_salary),job_id FROM t_mysql_jobs GROUP BY job_id; select * from lgs1
方式二:alter view 视图名 as 查询语句;
-- 修改为查询t_mysql_employees表信息 ALTER VIEW lgs1 AS SELECT * FROM t_mysql_employees; select * from lgs1
三、删除视图
语法:drop view 视图名,视图名,...;
DROP VIEW emp_v1,emp_v2,myv3;
四、查看视图
DESC myv3;
SHOW CREATE VIEW myv3;
五、视图的更新
-- 更新前 CREATE OR REPLACE VIEW lgs1 AS SELECT last_name,email,salary*12*(1+IFNULL(commission_pct,0)) "annual salary" FROM t_mysql_employees; -- 更新后 CREATE OR REPLACE VIEW myv1 AS SELECT last_name,email FROM t_mysql_employees;
视图操作:
1.插入 INSERT INTO myv1 VALUES('张飞','zf@qq.com'); #2.修改 UPDATE myv1 SET last_name = '张无忌' WHERE last_name='张飞'; #3.删除 DELETE FROM myv1 WHERE last_name = '张无忌';
具备以下特点的视图不允许更新
1,包含以下关键字的sql语句:分组函数、distinct、group by、having、union或者union all
2,常量视图
3,Select中包含子查询
4,join
5,from一个不能更新的视图
6,where子句的子查询引用了from子句中的表