SQL之子查询
2024-08-31 14:10:26
子查询概念:把一个查询的结果在另一个查询中使用就叫做子查询
1.子查询作为条件时
当我们使用子查询作为条件时,若子查询返回值为多个,则会报以下错误:
"子查询返回的值不止一个。当子查询跟随在 =、!=、<、<=、>、>= 之后,或子查询用作表达式时,这种情况是不允许的。"
此时我们应该使用范围【in】关键字来解决。
2.子查询的分类
a.独立子查询:可以独立来执行的查询语句做子查询使用
b.相关子查询:子查询使用了父查询中的列
3.子查询的使用方式
a.子查询作为条件使用:当父查询需要某个值,就可以用子查询给出。
b.子查询作为列的值
select ClassName from MyClass where ClassId=1
select StudentName,Gender,(select ClassName from MyClass where ClassId=1) from Student where ClassId=1
我们使用第一行代码作为列值,现在代码为正确的写法,但会有其他两种出错的写法。
i.
select StudentName,Gender,(select ClassName from MyClass) from Student where ClassId=1
由于没有写限定条件,子查询将返回一列多行多个值,会有如下报错:
j.
select StudentName,Gender,(select * from MyClass) from Student where ClassId=1
由于*代表了一行多列值,会有以下报错:
c.子查询作为结果集
i.
使用子查询结果集实现分页:
select top 3 *from Student--第一页
select top 3*from Student where StudentId not in(select top 3 StudentId from Student)--第二页
在这里我们先选择了第一页,一共三条数据,然后使用第一页的结果集作为第二页的查询条件,得出第二页不在这三条结果范围外的前三条结果。
j.
我们还可以使用ROW_NUMBER来实现分页效果,此函数为数据集提供一个连续的编号,我们用这些编号来实现分页。
select *,ROW_NUMBER()over(order by studentid) as id from Student
select *from(select *,ROW_NUMBER()over(order by studentid) as id from Student) as temp where id>0 and id<=5
select *from(select *,ROW_NUMBER()over(order by studentid) as id from Student) as temp where id>5 and id<=10
最新文章
- JAVA IO 字节流与字符流
- 项目支持Servlet3.0的新特性
- 【GOF23设计模式】解释器模式 &; 访问者模式
- 转:谷歌大脑科学家 Caffe缔造者 贾扬清 微信讲座完整版
- 解决IntelliJ IDEA 13更新FindBugs 0.9.993时JRE版本过低导致启动失败问题
- 【BZOJ 1084】[SCOI2005]最大子矩阵
- ASP 生成带日期的随机数
- win10系统调用架构分析
- 2013=12=2 bitree
- STL set 使用小结
- 使用cocoapods install友盟时报错Error installing UMengAnalytics
- 《CSS核心技术详解》
- HeadFirst设计模式读书笔记之工厂模式
- MySQL数据库的定时备份
- Python:Day14 集合、函数
- 5G到来,数据中心如何变革?
- JDK8的ConcurrentHashMap也会造成CPU 100%
- oracle服务器重启后无法进入系统,登录系统时提示model is unknow
- Java后端开发奋斗之路
- 钩子函数mounted: