子查询in
我们已经知道运算符in,它允许我们在WHERE子句中过滤某个字段的多个值。
where子句使用in语法
select column_name from table_name where column_name in(value1,value2,...)
如果运算符in后面的值是来源于某个查询结果,并非是指定的几个值,这时就需要用到子查询。子查询又称为内部查询或嵌套查询,即在SQL查询的WHERE子句中嵌入查询语句。
子查询in语法
select column_name from table_name
where column_name in(
select column_name from table_name[where]
);
子查询exists
exists是子查询中用于测试内部查询是否返回任何行的布尔运算符。将主查询的数据放到子查询中做条件验证,根据验证结果(TRUE或FALSE)来决定主查询的数据结果是否保留。
where子句使用exists语法
select column_name1
from table_name1
where exists(select * from table_name2 where condition);
示例:
#子查询in
#查询所有选修了课程的学生
select A.*
from student A
where A.stu_no in(select B.stu_no from score B);
#查询选修了离散数学的学生
select A.*
from student A
where A.stu_no in(select B.stu_no from score B where B.course='离散数学');
#子查询exists
#查询所有选修了课程的学生
select A.*
from student A
where exists(select * from score B where A.stu_no=B.stu_no);
#查询所有未选修课程的学生
select A.*
from student A
where not exists(select * from score B where A.stu_no=B.stu_no);