SQL中的子查询——可以结合聚合函数

1. 子查询的介绍

在一个 select 语句中,嵌入了另外一个 select 语句, 那么被嵌入的 select 语句称之为子查询语句,外部那个select语句则称为主查询.

主查询和子查询的关系:

1.子查询是嵌入到主查询中
2.子查询是辅助主查询的,要么充当条件,要么充当数据源
3.子查询是可以独立存在的语句,是一条完整的 select 语句

2. 子查询的使用

例1. 查询大于平均数学成绩的学生:

select * from students where math>(select avg(math) from students);

在这里插入图片描述
例2. 查询学生在班的所有班级名字:

select name from class where id in (select cid from students where cid is not null);

这样没有人的4班就不会显示了
在这里插入图片描述
例3. 查找年龄最大且成绩最低的学生:
原表:
在这里插入图片描述

select * from students where (math ,age)=(select min(math),max(age) from students);

在这里插入图片描述

3. 小结

子查询是一个完整的SQL语句,子查询被嵌入到一对小括号里面

发布了881 篇原创文章 · 获赞 1254 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/qq_35456045/article/details/105180611