一、基础知识:
1、含义:虚拟表,和普通表一样使用mysql5.1版本出现的新特性,是通过表动态生成的数据,比如:舞蹈班和普通班级的对比创建语法的关键字是否实际占用物理空间使用
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`;
二、创建视图:
语法: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%';
三、视图的修改:
create or replace view 视图名
as
查询语句;
*/
SELECT * FROM myv3
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 emp_v1,emp_v2,myv3;
四、查看视图:
DESC myv3;
SHOW CREATE VIEW myv3;
五、视图的更新:
CREATE OR REPLACE VIEW myv1
AS
SELECT last_name,email,salary*12*(1+IFNULL(commission_pct,0)) "annual salary"
FROM employees;
变化后:
CREATE OR REPLACE VIEW myv1
AS
SELECT last_name,email
FROM 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 = '张无忌';
六:具备以下特点的视图不允许更新:
①包含以下关键字的sql语句:分组函数、distinct、group by、having、union或者union all
②常量视图
③Select中包含子查询
④join
⑤from一个不能更新的视图
⑥where子句的子查询引用了from子句中的表