視圖(view)
定義:是一種有結(jié)構(gòu)亩鬼,但是沒(méi)有結(jié)果的虛擬表
創(chuàng)建視圖
基本語(yǔ)句? create view 視圖名字 as select 語(yǔ)句梢夯;
創(chuàng)建單表視圖? 基表只有一個(gè)?
創(chuàng)建多表視圖? 基表來(lái)源至少兩個(gè)
--視圖: 單表+ 多表
? ?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 s left join my_class as c on s.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?
外鏈接? 不符合條件不放入
內(nèi)鏈接? 符合條件放入
--查看視圖創(chuàng)建語(yǔ)句? ? show create view my_v3\G
查看視圖
show tables[like] / desc 視圖名/ show create table 視圖名
show create view my_v3\G? --查看視圖創(chuàng)建語(yǔ)句
show views? 不可以v查看所有視圖
show * from my_v1
show * from my_v2
show * from my_v3
修改視圖
alter view 視圖名字? as 新的select語(yǔ)句
alter view my_ v1 as? ? ? ? ? ? ? ? ? select id,name,age,sex,height,c_id from my_student
刪除視圖
drop view? 視圖名字
create view my_v4 as? ? ? ? ? ? ? ? select * from my_student? ? ? ? ? ? ? ? ---刪除視圖v4? ? ? ? ? ? ? ? ? drop table my_v4? ?--刪除失斂已(不能刪表)? ?drop? view my_v4? - -- 刪除成功
新增數(shù)據(jù)
{ 1 }多表視圖不能新增數(shù)據(jù)
---多表視圖不能插入數(shù)據(jù)? ?insert into my_v3 value(null,'bc20200008','張山','男',15,180,3,'Python1910','A204')? ? ? -----插入失敗
--將學(xué)生表的學(xué)號(hào)字段設(shè)置成不允許為空? ?alter tabel my_student modify number char(10) not null? unique? ??
{ 2 }? 可以向單表視圖插入數(shù)據(jù)懦冰,但是視圖中包含的字段必須有基表中所不能為空,或沒(méi)默認(rèn)值的字段
---單表視圖插入數(shù)據(jù)? : 視圖不包含所有不允許為空的字段? insert into my_v1 values(null,'張山','男',15,180,3)
--單表視圖插入數(shù)據(jù)? ?insert? into my_v2 values(2,'Python1903','A204')
{ 3 }? 視圖是可以向基表插入數(shù)據(jù)的
刪除數(shù)據(jù)
多表視圖不能刪除數(shù)據(jù)
單表視圖可以刪除數(shù)據(jù)
更新數(shù)據(jù)
更新限制? with check option
---視圖? age 字段限制更新
create view my_v4 as?
select * from? my_student where age>30 with cheak option
--表示視圖的數(shù)據(jù)來(lái)源都是年齡大于30歲 是由where age 》30 的
--將視圖可以查到數(shù)據(jù)改成年齡小與30? ?update my_v4 set? age = 29 where id = 5??
---可以修改數(shù)據(jù)源讓視圖可以查到 可以該? ? 但是無(wú)效果
uodate my_v4 set? age = 32 where id=3