mysql 子查询in和exists的使用

子查询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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值