MySQL(創(chuàng)建-查看-修改-刪除視圖、視圖新增-刪除-更新數(shù)據(jù))

mysql.exe -h localhost -P 3306 -u root -p

use mydb;?????——???? 進(jìn)入數(shù)據(jù)庫(kù)

查看:show index from 表名\G

desc:查看表結(jié)構(gòu)

select * from 表名:查詢所有數(shù)據(jù)?

視圖(view):是一種有結(jié)構(gòu),但是沒(méi)結(jié)果的虛擬表

視圖優(yōu)點(diǎn):對(duì)外提供友好型,不同的視圖對(duì)應(yīng)不同的數(shù)據(jù)

一、創(chuàng)建視圖

1)基本語(yǔ)法:create view 視圖名字 as select 語(yǔ)句;

2)創(chuàng)建單表視圖:基表只有一個(gè)

3)創(chuàng)建多表視圖:基表來(lái)源至少兩個(gè)

-- 視圖:?jiǎn)伪?多表

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 視圖名;

-- 查看視圖創(chuàng)建語(yǔ)句

show create view my_v3\G????-- \G:橫向查看

三、修改視圖

alter view 視圖名字 as 新的select語(yǔ)句;

-- 視圖使用

select * from my_v1;

select * from my_v2;

select * from my_v3;

-- 修改視圖

alter view my_v1 as

select id,name,age,sex,height,c_id from my_student;

四、刪除視圖

drop view 視圖名字;

-- 先創(chuàng)建v4

create view my_v4 as

select * from my_student;

-- 刪除視圖

drop view my_v4;

五、新增數(shù)據(jù)

1)多表視圖不能新增數(shù)據(jù)

-- 多表視圖不能插入數(shù)據(jù)

insert into my_v3 values(null,'bc20200008','張三豐','男',150,180,3,'Python1910','A204');

2)可以向單表視圖插入數(shù)據(jù),但是視圖中包含的字段必須有基表中所有不能為空、或沒(méi)有默認(rèn)值的字段

-- 將學(xué)生表的學(xué)號(hào)字段設(shè)置成不允許為空

alter table my_student modify number char(10) not null unique;

-- 單表視圖插入數(shù)據(jù):視圖不包含所有不允許為空的字段

insert into my_v1 values(null,'張三豐',150,'男',180,3);

3)視圖是可以向基表插入數(shù)據(jù)的

-- 單視圖插入數(shù)據(jù)

insert into my_v2 values(3,'Python1910','A204');

六、刪除數(shù)據(jù)

1)多表視圖不能刪除數(shù)據(jù)

-- 多表示圖不能刪除數(shù)據(jù)

delete from my_v3 where id=1;

2)單表視圖可以刪除數(shù)據(jù)

-- 單表視圖刪除數(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 check 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;

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容