【sql编程1_1】sql查询 同一个字段 同时满足多个条件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40643642/article/details/88365583

emp表:     works表:    

题目:查询同时工作于"硬件"和"软件"两个部门的每个雇员的名字和年龄

select ename,age
from emp
WHERE eid in 
(select eid 
from works 
where did = '软件' or did = '硬件'
GROUP BY eid
having count(eid) = 2)

该SQL语句执行过程可看作:子查询中where子句首先过滤行,留下第2、3、5、6行,group by再进行分组,having过滤分组,count(eid)不为2的分组被过滤掉,最后留下eid = 017,再执行父查询。

ps:1.group by必须写在where子句之后,order by 子句之前

2.注释掉第6行 where子句,子查询结果为 017和020

3.where用来过滤行,having用来过滤分组。where在数据分组前进行过滤,having在数据分组后进行过滤。whee排除的行不包括在分组中。

4.having支持所有where操作符

猜你喜欢

转载自blog.csdn.net/weixin_40643642/article/details/88365583