子查询的使用

子查询

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

主查询和子查询的关系:

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

2.子查询的使用

查询大于平均年龄的学生:
select * from students where age > (select avg(age) from students);
查询学生在班的所有班级名字:
select name from classes where id in (select cls_id from students where cls_id is not null);
 查找年龄最大,身高最高的学生:
 select * from students where (age, height) =  (select max(age), max(height) from students);

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

猜你喜欢

转载自blog.csdn.net/li944254211/article/details/109265876