#进阶16 : 视图 /* 含义: 虚拟表,和普通表一样使用;(从5.1开始使用的:)是通过表动态生成的数据 创建语法: create view 视图名 as 查询语句; ---------- 作用: 重用SQL语句,简化复杂的sql操作,不必知道它的查询细节; 保护数据,提高安全性; ------------------------- 视图的修改: 方式1: create or replace view 视图名 as 查询语句; 方法2: alter view 视图名 as 查询语句; ---------------------------- 三:视图的删除 : 用户可以一次删除一个或者多个视图,前提是必须有该视图的drop权限。 语法: drop view 视图名,视图名,视图名; ----------------------------- 四:查看视图 desc v2; ----------------------------- #五: 视图的更新 CREATE OR REPLACE VIEW myv1 AS SELECT last_name,email FROM employees; SELECT * FROM myv1 ORDER BY last_name DESC; #1.插入 INSERT INTO myv1 VALUES('张飞','zafqq.com'); #2 修改 UPDATE myv1 SET last_name ='张无忌' WHERE last_name='张飞'; #3 删除 DELETE FROM myv1 WHERE last_name ='张无忌'; -------------------------------------------- #六 视图的可更新性 视图的可更新性和视图中查询的定义有关系,以下类型的视图是不能更新的。 • 包含以下关键字的sql语句:分组函数、distinct、group by 、having、union或者union all • 常量视图 • Select中包含子查询 • join • from一个不能更新的视图 • where子句的子查询引用了from子句中的表 --------------------------------------------- 视图 : create view 没有占用多少物理空间,只保存sql逻辑 表 : create table 占用了 */ #案例():查询姓张的学生名和专业名 USE student; SELECT studentname,majorname FROM stuinfo s INNER JOIN major m ON s.`majorid`=m.`majorid` WHERE s.`studentname` LIKE '张%'; #demo1: 创建视图 ; CREATE VIEW v1 AS SELECT studentname,majorname FROM stuinfo s INNER JOIN major m ON s.`majorid`=m.`majorid` WHERE s.`studentname` LIKE '张%'; #然后从视图中查找出全部信息; SELECT * FROM v1 WHERE studentname LIKE '张%'; #---------------------------- #1.查询邮箱中包含a字符的 员工名、部门名和工种信息 CREATE VIEW v2 AS SELECT e.`last_name`,e.`department_id`,j.`job_id`,j.job_title FROM employees e,jobs j WHERE e.`job_id`=j.`job_id` AND email LIKE '%a%'; #② 使用视图 SELECT * FROM v2 WHERE last_name LIKE '%a%'; #2.查询各部门的平均工资的级别 CREATE VIEW v3 AS SELECT AVG(salary) ag,department_id FROM employees GROUP BY department_id; SELECT v3.department_id,g.`grade_level` FROM v3 JOIN job_grades g ON v3.ag BETWEEN g.`lowest_sal` AND g.`highest_sal`; #3.查询平均工资最低的部门信息 SELECT * FROM v3 ORDER BY ag LIMIT 1; #4.查询平均工资最低的部门名和工资 SELECT * FROM `departments` WHERE departments.department_id = ( SELECT department_id FROM v3 ORDER BY ag LIMIT 1 ); #5.视图的修改(REPLACE)--方式1 CREATE OR REPLACE VIEW v3 AS SELECT MIN(salary) min_ag,department_id FROM employees GROUP BY department_id; SELECT * FROM v3; #6.视图的修改(alter)--方式2 ALTER VIEW v3 AS SELECT MAX(salary) max_ag,department_id FROM employees GROUP BY department_id; #平均1.00 -- 2400次 SELECT ('28-29两天scanner sum'),( 865-833+621-523+230-175+3+ 58-41+87-66+4+48-32+7+2+20+31-14+11-9 ),(0.054+0.073); #五: 视图的更新 CREATE OR REPLACE VIEW myv1 AS SELECT last_name,email FROM employees; SELECT * FROM myv1 ORDER BY last_name DESC; #1.插入 INSERT INTO myv1 VALUES('张飞','zafqq.com'); #2 修改 UPDATE myv1 SET last_name ='张无忌' WHERE last_name='张飞'; #3 删除 DELETE FROM myv1 WHERE last_name ='张无忌';