某列同时满足两个条件

比如用户和角色的中间表:

想查找同时拥有角色id为1和2的用户id,sql如下:

select
    user_id
from
    user_role
group by
    user_id
having
    sum(case when role_id=1 then 1 else 0 end)>0
and
    sum(case when role_id=2 then 1 else 0 end)>0
原文地址:https://www.cnblogs.com/drizzlewithwind/p/8533484.html