視圖(view):是一種有結(jié)構(gòu),但是沒結(jié)果的虛擬表
創(chuàng)建視圖
基本語(yǔ)法:create view 視圖名字 as select 語(yǔ)句;
創(chuàng)建單表視圖:基表只有一個(gè)
創(chuàng)建多表視圖:基表來(lái)源至少兩個(gè)
視圖:?jiǎn)伪砗投啾?/b>
create view my_v1 as
select * from my_student;
create view my_v2 as
select * from my_class;
create view my_v3 as
select * from my_student as a left join my_class as
c on s.c_id=c.id;-- 錯(cuò)誤,id重復(fù)
多表
create view my_v3 as
select s.*,c.c_name,c.room from my_student as s
join my_class as c on s.c_id=c.id;
查看視圖
show tables [like] / desc 視圖名 / show create table 視圖名;
-- c查看視圖創(chuàng)建語(yǔ)句
show create view my_v3\G(\G橫向查看)
修改視圖
alter view 視圖名字 as 新的select語(yǔ)句;
alter view my_v1 as
select id,name,age,sex,height,c_id from my_student;
刪除視圖
drop view 視圖名字;
drop view my_v4;
視圖數(shù)據(jù)操作
新增數(shù)據(jù)
多表視圖不能新增數(shù)據(jù)
可以向單表視圖插入數(shù)據(jù)
insert into my_v2 values(3,'Python1910','A204');
視圖中包含的字段必須有基表中所有不能為空、或沒有默認(rèn)值的字段
insert into my_v1 values(null,'陳立農(nóng)',130,'男',183,3);
視圖是可以向基表插入數(shù)據(jù)的
刪除數(shù)據(jù)
多表視圖不能刪除數(shù)據(jù)
delete from my_v3 where id=1;
單表視圖可以刪除數(shù)據(jù)
delete from my_v2 where id=4;
更新數(shù)據(jù)
更新限制:with check option;
多表視圖更新數(shù)據(jù)
update my_v3 set c_id=4 where id=6;
視圖:age字段限制更新
create view my_v4 as
select * from my_student where age>30 with check option;
-- 表示視圖的數(shù)據(jù)來(lái)源都是年齡大于30的,是由where age>30決定的
-- with chhheck
-- option決定通過(guò)視力更新的時(shí)候,不能將已經(jīng)得到的數(shù)據(jù)age>30的改成<30的
-- 將視圖可以查到的數(shù)據(jù)改成年齡小于30
update my_v4 set age=29 where id=5;
-- 可以修改數(shù)據(jù)讓視圖可以查到:可以改,但是無(wú)效果
update my_v4 set age=32 where id=3;?
視圖算法
視圖算法:系統(tǒng)對(duì)視圖以及外部查詢視圖的select語(yǔ)句的一種解析方式
視圖算法分三種
undefined:未定義(默認(rèn)的)
temptable:臨時(shí)表算法
merge:合并算法
算法指定:在創(chuàng)建視圖的時(shí)候create algorithm=指定算法 view 視圖名字 as select語(yǔ)句;