当前位置:网站首页>【数据库和SQL学习笔记】8.SQL中的视图(view)
【数据库和SQL学习笔记】8.SQL中的视图(view)
2022-08-05 05:15:00 【takedachia】
工具:SQL Server 2019 Express
操作系统:Windows 10
用到的数据库备份: teaching.bak
回顾一下表结构:
t_student (S#, Sname, Sex, Age, Major)
t_teacher (T#, Tname, Age, Title)
t_course (C#, Cname, T#)
t_student_course (S#, C#, Score)
视图(view)
我们在平时工作中,把数据库的数据呈现给用户,就需要简化用户的数据观点。
我们可以把分散在多张表中的数据,通过视图View定义在一起,这样用户就不必输入一些复杂的查询语句,只需要针对视图做简单查询即可。
这样可以更好地适应不同用户对数据的需求;同时这样为用户划定了访问数据的范围,有利于数据的保密。
视图是是一个虚拟表,其内容由查询定义。同真实的表一样,视图包含一系列带有名称的列和行数据。
但是,视图并不在数据库中以存储的数据值集形式存在。行和列数据来自由定义视图的查询所引用的表,并且在引用视图时动态生成。
创建视图(create view)
创建视图:
create view student_male
as select Sname, Cname, Score
from t_student, t_student_course, t_course
where t_student.S#=t_student_course.S# and t_student_course.C#=t_course.C#
and Sex='男'
执行后,可在对象资源管理器中打开数据库下的视图,可找到我们创建的视图:
我们可以指定显示的列名:
create view student_male_detail(Name, Course, Score)
as select Sname, Cname, Score
from t_student, t_student_course, t_course
where t_student.S#=t_student_course.S# and t_student_course.C#=t_course.C#
and Sex='男'
创建后,我们选择该视图,右键点选“选择前1000行”就可以看到信息了。
修改视图(alter view)
比如新增一列:
alter view student_male_detail
as select t_student.S#, Sname, Cname, Score
from t_student, t_student_course, t_course
where t_student.S#=t_student_course.S# and t_student_course.C#=t_course.C#
and Sex='男'
效果:
删除视图(drop view)
删除 student_male_detail 视图
drop view student_male_detail
效果:
如何使用视图
创建视图后,就可以直接当作一张表来使用。
可直接使用from子句。
例1:查询所有男生的平均分:
select avg(Score)
from student_male
效果:
如果我们不利用视图,查询就变成:
select avg(Score)
from t_student, t_student_course
where t_student.S#=t_student_course.S# and Sex='男'
所以利用视图可以简化查询。
例2:查询每一名男生的考试成绩平均分:
边栏推荐
- What are the characteristics of the interface of the physical layer?What does each contain?
- flink项目开发-配置jar依赖,连接器,类库
- DOM及其应用
- [Go through 11] Random Forest and Feature Engineering
- 数据库期末考试,选择、判断、填空题汇总
- flink实例开发-详细使用指南
- Kubernetes常备技能
- flink yarn-session的两种使用方式
- vscode+pytorch使用经验记录(个人记录+不定时更新)
- [Go through 3] Convolution & Image Noise & Edge & Texture
猜你喜欢
[Go through 8] Fully Connected Neural Network Video Notes
SQL(二) —— join窗口函数视图
flink基本原理及应用场景分析
【过一下4】09-10_经典网络解析
Flink Distributed Cache 分布式缓存
Calling Matlab configuration in pycharm: No module named 'matlab.engine'; 'matlab' is not a package
[Go through 10] sklearn usage record
【零基础开发NFT智能合约】如何使用工具自动生成NFT智能合约带白名单可Mint无需写代码
[Go through 4] 09-10_Classic network analysis
Flink HA配置
随机推荐
关于基于若依框架的路由跳转
第三讲 Gradient Tutorial梯度下降与随机梯度下降
【过一下11】随机森林和特征工程
SparkML-初探-文本分类
解决:Unknown column ‘id‘ in ‘where clause‘ 问题
学习总结week3_1函数
软件设计 实验四 桥接模式实验
day10-字符串作业
vscode要安装的插件
The software design experiment four bridge model experiment
学习总结day5
[Remember 1] June 29, 2022 Brother and brother double pain
Flink Distributed Cache 分布式缓存
物理层的接口有哪几个方面的特性?各包含些什么内容?
Matplotlib(三)—— 实践
spingboot 容器项目完成CICD部署
Lecture 5 Using pytorch to implement linear regression
基于Flink CDC实现实时数据采集(三)-Function接口实现
实现跨域的几种方式
学习总结week2_4