视图概述
- 视图是一张虚拟表。
- 视图的存在形式是一组SQL语句,其数据来源于引用的真实表,其自身并不存储数据。并且数据是引用视图时动态生成的。
- 具有和表相同的查询操作方法,以及受限制的更新、删除、修改等。这里可以参考官方文档 视图的限制。没读懂~~
- 集中分散数据。
- 简化查询语句。
- 重用SQL语句。
- 保护数据安全。
- 共享所需数据。
- 更改数据格式。
创建视图
create view
--创建简单视图 v_student。
--or replace 可选项,如果视图已存在,则替换已有的同名视图,如果视图不存在,重新创建视图。
create [or replace] view v_student as
select * from tb_student;
--创建带检查约束的视图
--with check option子句要求视图修改时,需要符合select子句中指定的限制条件。
create view v_student as
select * from tb_student where sex='男'
with check option;
--创建基于多表的视图
create view v_student as
select studentNo,studentName
from tb_student, tb_score
where tb_student.classNo=tb_score.classNo;
--创建基于视图的视图
create view v_student as
select * from v_score
where score>90;
--创建带表达式的视图
--这里指定'Avgscore'来命名聚合函数
create view v_student(studentNo,Avgscore) as
select studentNo, avg(score) from tb_student;
修改视图
alter view
--修改视图,使视图的修改都符合学生性别为‘男’,民族为‘汉’的条件。
alter view v_student(studentNo,studentName,classNo) as
select studentNo,studentName,classNo from tb_student
where sex='男' and nation='汉'
with check option;
查看视图
show create view v_student;
删除视图
--if exists 为可选项,如果不指定,当视图不存在时,会报错。
drop view if exists v_student;
视图数据操作(跟表相同)
--查询视图中的数据
select studentNo from v_student where classNo='111';
--视图中插入数据
insert into v_score values('2014310101','31005',95);
--修改视图中的数据
update v_student set native='汉';
--删除视图中的数据
delete from v_student where studentName='周明';
课后习题
1、创建视图content_view
--切换数据库
use db_test;
--创建视图
create view content_view as
select * from content
where username='mysql初学者'
with check option;
2、创建视图v_score
use db_score;
create view v_score as
select * from tb_score
where score>90
with check option;
3、查找视图v_score中的数据
select studentNo,score from v_score
where classNo='21002';
4、向视图v_score中插入一条记录
insert into v_score
values('2014310101','31005',95);
5、删除视图v_score中记录
delete from v_score
where studentNo='2014310101';