sql子查询

目录

1、什么是子查询

2、子查询分类

        2.1按照子查询位置分类

2.1.1 select子查询

2.1.2 from子查询

2.1.3 where子查询

2.1.4 having子查询

2.1.5 exits子查询

        2.2按照子查询结果分类

2.2.1 标量子查询

2.2.2 列子查询

2.2.3 行子查询

2.2.4 表子查询


1、什么是子查询

        子查询又称嵌套查询,指嵌套在sql语句中使用的查询,它可以嵌套在主查询中的SELECT,INSERT,UPDATE或DELETE语句中,或者在另一个子查询中。子查询可以是一个完整的SELECT语句(也可以包括ORDER BY, GROUP BY等子句),或者只是SELECT语句的一部分(如WHERE子句中的条件)。

2、子查询分类

        以scores表的查询作简单的示例,以便于帮助区分不同类别子查询的差异,scores表的表结构如上图所示

        2.1按照子查询位置分类

2.1.1 select子查询

select (select count(*) from scores where score1>=60)/(select count(*)
from scores) as 比例 from dual	
#SELECT子查询在SELECT子句中使用查询的结果(一般会和dual空表一起使用),
#这里求的是分数大于60分的同学占所有学生的比例

2.1.2 from子查询

select stuName,score1 from 
(select stuName,score1 from scores group by stuName having score1>66) stu_score1 
where stu_score1.score1>90

2.1.3 where子查询

select * from scores where score1>(select avg(score1) from scores)

2.1.4 having子查询

select * from scores group by stuName having score1>78

2.1.5 exits子查询

select * from scores where exists (select * from scores where score1>90)	
#只要有一条查询满足exist里面的条件,exist子查询则返回true,
#外层的select即能执行(即返回scores表的所有记录),否则返回false

       

         2.2按照子查询结果分类

2.2.1 标量子查询

  • 子查询返回结果:单个值(数字、字符串、日期等)
  • 常用的操作符包括:=、<>、>、>=、<、<=
select * from scores where score1=(select score1 from scores where stuNo=12)

2.2.2 列子查询

  • 子查询返回结果:一列(可以是多行)
  • 常用的操作符包括:IN、NOT IN、ANY、SOME、ALL
select stuName from scores where stuNo in
 (SELECT stuNo FROM stu_scores.scores where score1=78)

2.2.3 行子查询

  • 子查询返回结果:一行(可以是多列)
  • 常用的操作符包括:=、<>、IN、NOT IN
 select stuNo from scores where (stuName,score1) in 
(select stuName,score1 from scores where score1=78)

2.2.4 表子查询

  • 子查询返回结果:多行多列
  • 常用的操作符:IN,EXISTS
select stuNo from scores where exists (select * from scores where score1=78)
  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值