SQL选择多行验证条件的用户

时间:2017-08-14 11:09:48

标签: mysql sql

我有下表:

table services-users

第一列包含Services_ID,第二列包含Users_ID,第三列表示用户是否已启用该服务。 我需要确定(用户一次)允许哪些用户使用ID 4和5的两种服务。

我用Mysql写了那个查询:

SELECT DISTINCT User 
  FROM tablexxx
 WHERE Service IN (4, 5)
   AND User NOT IN (SELECT User
                      FROM tablexxx
                     WHERE Service IN (4, 5)
                       AND Active = FALSE);

该查询有效,但有没有更好的技术方法来编写它?

正确的结果是:

Result

1 个答案:

答案 0 :(得分:3)

select user
from your_table
where service in (4,5)
and active = TRUE
group by user
having count(distinct service) = 2

select user
from your_table
group by user
having sum(active = TRUE and service = 4) > 0
   and sum(active = TRUE and service = 5) > 0