什麼是檢視
有結構沒結果的臨時表
- 有結構意味著, 檢視是一個有行有列的二維表
- 沒結果意味著, 檢視中並沒有真實存放的資料
- 檢視中的資料, 從基表中獲取
檢視就是一個零庫存的經銷商
檢視的優點
- 可以複用程式碼, 節省SQL語句, 以後可以直接操作檢視
- 可以隔離表結構, 隱藏關鍵資料, 只向外提供必要的資料
- 檢視主要針對查詢, 刪除檢視, 不會影響資料
- 檢視可以把資料分級, 不同的許可權, 給不同的檢視(資料)
建立
建立檢視之前, 我們需要一些測試資料


drop database if exists new_library;
create database new_library CHARACTER set utf8;
use new_library;
drop table if exists readertype;
create table readertype(
retypeid int not null primary key,
typename VARCHAR(20) not null,
borrowquantity int not null,
borrowday int
);
drop table if exists reader;
create table reader(
readerid char(10) not null PRIMARY key,
readername VARCHAR(20) not null,
readerpass VARCHAR(20) not null,
retypeid int,
readerdate datetime,
readerstatus VARCHAR(4),
FOREIGN key(retypeid) REFERENCES readertype(retypeid)
);
insert into readertype values
(1,'學生',10,30),
(2,'教師',20,60),
(3,'管理員',15,30),
(4,'職工',15,20);
insert into reader values
('0016','蘇小東','123456',1,'1999-9-9','有效'),
('0017','張明','123456',1,'2010-9-10','有效'),
('0018','樑君紅','123456',1,'2010-9-10','有效'),
('0021','趙清遠','123456',2,'2010-7-1','有效'),
('0034','李瑞清','123456',3,'2009-8-3','有效'),
('0042','張明月','123456',4,'1997-4-23','有效');
複製程式碼
建立一個檢視, 用來查詢讀者的詳細資訊, 包括使用者id, 姓名, 類別名稱, 借書數量
如果不使用檢視, 我們可以使用連表查詢

有了檢視, 我們就可以把複雜的查詢放入檢視之中
drop view if exists reader_detail;
create view reader_detail as
select
readerid,readername,typename,borrowquantity
from
reader,readertype
where
reader.retypeid = readertype.retypeid;
複製程式碼
檢視檢視
因為檢視是一張虛擬表, 所有檢視錶的命令, 檢視都能用
show tables;
desc reader_detail;
show create table reader_detail;
複製程式碼




既然檢視是臨時表, 那必然會有結構檔案.frm

使用檢視
像表一樣查詢資料即可

修改檢視
可以使用alter
在原有檢視的基礎上, 加入欄位讀者狀態

也可以使用create or replace
在另一個檢視中, 增加讀者姓名欄位

刪除檢視
drop view 檢視名稱; -- 不能使用table
複製程式碼

也可以一次刪除多個
drop view 檢視1, 檢視2....;
複製程式碼
檢視重新命名
rename table 原來的名字 to 新名字;
複製程式碼


檢視中的資料, 可以增刪改嗎?
可以, 但是不推薦這麼做, 檢視主要是查詢資料時使用

因為不能操作多表, 所以我們新建一個單表的檢視
drop view if exists select_reader;
create view select_reader as select readerid,readername from reader;
複製程式碼
檢視進行insert操作

向檢視中插入一條資料
insert into select_reader values(123,'LUCY');
複製程式碼

檢視進行update操作

注意with check option

檢視進行delete操作

