0
点赞
收藏
分享

微信扫一扫

浅谈——视图

kiliwalk 2022-03-16 阅读 44
sql数据库

一、什么是视图?

网上视图的定义很详细,但也很复杂,难理解,所以我就把我所理解的拆散来让你们能懂。

        视图简单来说就是一张虚拟的表,它只提供查询。

说白了,视图,就是封装。好比如手机,我把软件装进去后就能直接按照它的规则运行、使用。

二、一个简单的视图怎么创建?

1、老规矩,先附上测试代码:

create database test01;    --创建数据库
use test01;    --进入数据库


--创建学生表
create table student(
	id  int   not null  primary key  identity(1,1),	--主键自增,
	student_no   varchar(20)  not null,	--学号
	student_name  varchar(20)  not null,	--姓名
	subject_no   int   not null,	--课程表对应的号
	subject_name varchar(20)  not null,	--课程名
	score   int  not null	--成绩
);


--插入学生信息
insert  into student(student_no , student_name , subject_no , subject_name , score )
 values( 201601 , '张三' , 0001 , '数学' , 98),
( 201601 , '张三' , 0002 , '语文' , 66),
( 201602 , '李四', 0001 , '数学' , 60),
( 201602 , '李四' , 0003 , '英语' , 78),
( 201603 , '王五' , 0001 , '数学' , 99),
( 201603 , '王五' , 0002 , '语文' , 99),
( 201603 , '王五' , 0003 , '英语' , 98)
;

2、这里列出视图的书写格式吧:

--创建视图
create view 视图名
as    
	SQL语句
;


--查看视图
select * from 视图名;

3、小练习:

--写一个视图,存放student_name/subject_name/subject_no/score字典的数据

create view demo01 --创建视图
as --编写SQL语句
	select student_name,subject_no,subject_name,score from student
;

查看视图得到:

 

小练习2:-写一个视图,存放语文成绩低于80分的同学student_no,student_name,subject_name,score

create view demo02     --创建视图
as --编写SQL语句
	select student_no,student_name,subject_name,score from student where subject_name='语文' and score<80
;

查看视图得到:

 小练习3:--写一个视图,存放王姓学生的student_name.subject_name,score

create view demo03 --创建视图
as    --编写SQL语句
	select student_name,subject_name,score from student where student_name like'王%'
;

查看视图得到:

 

三、总结

        通过上面几个小练习,不难看出,视图就是把sql语句封装起来,想要使用时直接运行得到结果。

        所以,难得不是视图,而是sql语句本身的编写。

举报

相关推荐

0 条评论