[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

快速跳转

相关文章
相关标签/搜索