总览:
细节:
or replace
;创建视图可加可不加;、
-- 创建视图
create or replace view stu_v_1 as select id,name from student where id <= 10;
-- 查询视图
show create view stu_v_1;
select * from stu_v_1;
select *from stu_v_1 where id < 3;
-- 修改视图
create or replace view stu_v_l as select id,name,no from student where id <= 10;
alter view stu_v_1 as select id,name from student where id <= 10;
-- 删除视图
drop view if exists stu_v_1;
create or replace view stu_v_1 as select id,name from student where id <= 20;
select * from stu_v_1;
insert into stu_v_1 values(6,"Tom');
create or replace view stu_v_1 as select id,name from student where id <= 20;
select * from stu_v_1;
insert into stu_v_1 values(6,"Tom');
insert into stu_v_1 values(30,"Tom');
where id <= 20
select * from stu_v_1;
,查看不到修改后的视图with cascaded check option
或者with local check option
WITH CHECK OPTION
子句创建视图时,MySQL会通过视图检查正在更改的每个行,例如 插入,更新,删除,以使其符合视图的定义。CASCADED 和LOCAL的区别:
演示cascaded:
with cascaded check option
-- cascaded
create or replace view stu_v_1 as select id,name from student where id <= 20;
insert into stu_v_1 values(5,"Tom'); //无检查,插入成功
insert into stu_v_1 values(25,"Tom'); //无检查,插入成功
create or replace view stu_v_2 as select id,name from sty_v_1 where id >= 10 with cascaded check option ;
insert into stu_v_2 values(7,"Tom'); //有检查,插入失败
insert into stu_v_2 values(26,"Tom'); //有检查,级联v1检查,插入失败
insert into stu_v_2 values(15,"Tom'); //有检查,满足条件插入成功
create or replace view stu_v_3 as select id,name from stu_v_2 where id <= 15 ;
insert into stu_v_3 values(11,"Tom'); //无检查,v2有检查,级联v1有检查,插入成功
insert into stu_v_3 values(17,"Tom'); //无检查,v2有检查,级联v1有检查,插入成功
insert into stu_v_3 values(28,"Tom'); //无检查,v2有检查,级联v1有检查,插入失败
演示local:
with local check option
--local
create or replace view stu_v_1 as select id,name from student where id <= 15;
insert into stu_v_4 values(5,"Tom'); //无检查,插入成功
insert into stu_v_4 values(16,"Tom'); //无检查,插入成功
create or replace view stu_v_2 as select id,name from stu_v_1 where id >= 10 with local check option ;
insert into stu_v_5 values(2,"Tom'); //有检查,插入失败
insert into stu_v_5 values(13,"Tom'); //有检查,递归到v1,无检查,插入成功
insert into stu_v_5 values(17,"Tom'); //有检查,递归到v1,无检查,插入成功
create or replace view stu_v_3 as select id,name from stu_v_2 where id < 20 ;
insert into stu_v_6 values(14,"Tom"); //无检查,递归到v2,有检查,低轨道v1,无检查,插入成功
需求:
-- 案例: 本质都是封装
-- 1.为了保证数据库表的安全性,开发人员在操作tb_user表时,
只能看到的用户的基本字段,屏蔽手机号和邮箱两个字段。
-- 单纯不选择手机号和邮箱两个字段即可
create view tb_user_view as
select id,name,profession,age,gender,status,createtime
from tb_user;
select *from tb user view;
-- 2.查询每个学生所选修的课程(三张表联査),这个功能在很多的业务中都有使用到,为了简化操作,定义一个视图。
-- 未封装前
select s.name,s.no .
from student s, student _course sc , course c
where s.id = sc.studentid and sc.courseid = c.id
create view tb stu course view as
select s.name student name , s.no student no , c.name course name
from student s, student_course sc , course c
where s.id =sc.studentid and sc.courseid =c.id;
select * from tb_stu_course_view;