[MySQL光速入門]028 聊聊視圖

什麼是視圖

有結構沒結果的臨時表sql

  • 有結構意味着, 視圖是一個有行有列的二維表
  • 沒結果意味着, 視圖中並無真實存放的數據
  • 視圖中的數據, 從基表中獲取

視圖就是一個零庫存的經銷商數據庫

視圖的優勢

  • 能夠複用代碼, 節省SQL語句, 之後能夠直接操做視圖
  • 能夠隔離表結構, 隱藏關鍵數據, 只向外提供必要的數據
  • 視圖主要針對查詢, 刪除視圖, 不會影響數據
  • 視圖能夠把數據分級, 不一樣的權限, 給不一樣的視圖(數據)

建立

建立視圖以前, 咱們須要一些測試數據post

image.png

image.png

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, 姓名, 類別名稱, 借書數量測試

若是不使用視圖, 咱們可使用連表查詢ui

image.png

有了視圖, 咱們就能夠把複雜的查詢放入視圖之中spa

drop view if exists reader_detail;

create view reader_detail as 
select 
	readerid,readername,typename,borrowquantity 
from 
	reader,readertype 
where 
	reader.retypeid = readertype.retypeid;
複製代碼

查看視圖

由於視圖是一張虛擬表, 全部查看錶的命令, 視圖都能用3d

show tables;
desc reader_detail;
show create table reader_detail;
複製代碼

image.png

image.png

image.png

image.png

既然視圖是臨時表, 那必然會有結構文件.frmcode

image.png

使用視圖

像表同樣查詢數據便可cdn

image.png

修改視圖

可使用alter 在原有視圖的基礎上, 加入字段讀者狀態blog

image.png

也可使用create or replace 在另外一個視圖中, 增長讀者姓名字段

image.png

刪除視圖

drop view 視圖名稱; -- 不能使用table
複製代碼

image.png

也能夠一次刪除多個

drop view 視圖1, 視圖2....;
複製代碼

視圖重命名

rename table 原來的名字 to 新名字;
複製代碼

image.png

image.png

視圖中的數據, 能夠增刪改嗎?

能夠, 可是不推薦這麼作, 視圖主要是查詢數據時使用

MySQL視圖.png

由於不能操做多表, 因此咱們新建一個單表的視圖

drop view if exists select_reader;

create view select_reader as select readerid,readername from reader;
複製代碼

視圖進行insert操做

image.png

向視圖中插入一條數據

insert into select_reader values(123,'LUCY');
複製代碼

image.png

視圖進行update操做

image.png

注意with check option

image.png

視圖進行delete操做

image.png

image.png

快速跳轉

相關文章
相關標籤/搜索