子查询概念:把一个查询的结果在另一个查询中使用就叫做子查询

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

最新文章

  1. JAVA IO 字节流与字符流
  2. 项目支持Servlet3.0的新特性
  3. 【GOF23设计模式】解释器模式 &amp; 访问者模式
  4. 转:谷歌大脑科学家 Caffe缔造者 贾扬清 微信讲座完整版
  5. 解决IntelliJ IDEA 13更新FindBugs 0.9.993时JRE版本过低导致启动失败问题
  6. 【BZOJ 1084】[SCOI2005]最大子矩阵
  7. ASP 生成带日期的随机数
  8. win10系统调用架构分析
  9. 2013=12=2 bitree
  10. STL set 使用小结
  11. 使用cocoapods install友盟时报错Error installing UMengAnalytics
  12. 《CSS核心技术详解》
  13. HeadFirst设计模式读书笔记之工厂模式
  14. MySQL数据库的定时备份
  15. Python:Day14 集合、函数
  16. 5G到来,数据中心如何变革?
  17. JDK8的ConcurrentHashMap也会造成CPU 100%
  18. oracle服务器重启后无法进入系统,登录系统时提示model is unknow
  19. Java后端开发奋斗之路
  20. 钩子函数mounted:

热门文章

  1. windows中安装redis的phpredis扩展
  2. c/s winform打包和部署
  3. Building Block[HDU2818]
  4. 多帧图片转gif
  5. oracle调优使用到相关sql
  6. submile 安装,汉化,插件
  7. 我的nginx+php是如何配置的?
  8. Run-time type information--RTTI
  9. Mysql 分库分表方案
  10. python_元组、字典