含义
虚拟表,它的数据来自于表,通过表动态生成。
案例:查询姓张的学生名和专业名
# 创建视图
create view v1
as
select stuname,majorname
from stuinfo s
inner join major m on s.majorid=m.id;
#使用视图
select * from v1
where s.stuname like "张%";
好处
- 简化sql语句
- 提高了sql的重用性
- 保护基表的数据,提高了安全性
创建
语法
create view 视图名
as
查询语句;
案例1:查询姓名中含a字符的员工名,部门名和工种信息
create view myv1
as
select last_name,department_name,job_title
from employees e
inner join departments d on e.department_id=d.department_id
inner join jobs j on j.job_id=e.job_id;
select * from myv1
where last_name like '%a%';
案例2:查询各部门的平均工资级别
create view myv2
as
select department_id,avg(salary) 平均工资
from employees e
group by department_id;
select department_id,平均工资,grade_level from myv2
inner join job_grades
on 平均工资 between lowest_sal and highest_sal;
# 也可以子查询
select department_id,平均工资,grade_level
from job_grades
inner join (
select department_id,avg(salary) 平均工资
from employees e
group by department_id
) av
on av.平均工资 between lowest_sal and highest_sal;
案例3:查询平均工资最低的部门信息
select * from myv2 order by 平均工资 limit 1
# 也可以子查询
select * from departments d
inner join (
select department_id,avg(salary) 平均工资
from employees
group by department_id
) av
on d.department_id=av.department_id
order by av.平均工资 limit 1;
修改
方式一
create or replace view 视图名
as
查询语句;
方式二
alter view 视图名
as
查询语句
删除
drop view 视图1,视图2,...;
查看
desc 视图名;
# 或者
show create view 视图名;
使用
create or replace view v
as
select last_name,email
from employees;
# 插入
insert into v values('张飞','zf@qq.com');
# 修改
update v set last_name = '张无忌' where last_name = '张飞';
# 删除
delete from v where last_name = '张无忌';
注意:视图一般用于查询的,而不是更新的,所以具备以下特点的视图都不允许更新
1.包含分组函数、group by、distinct、having、union、join
2.常量视图
3.where后的子查询用到了from中的表
4.用到了不可更新的视图
视图和表的对比
关键字 | 是否占用物理空间 | 使用 | |
---|---|---|---|
视图 | view | 占用较小,只保存sql逻辑 | 一般用于查询 |
表 | table | 保存实际的数据 | 增删改查 |
如果有其他问题欢迎留言或邮件提问
QQ:1269112498
Email:1269112498@qq.com
相关文章