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

时间:2022-02-11 12:28:35

I have the following table:

我有下表:

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

the first column contains Services_ID, the second Users_ID and the third indicates if the user is enabled for the service. I need to identify (one time for user) which users are allowed for both services with ID 4 and 5.

第一列包含Services_ID,第二列包含Users_ID,第三列表示用户是否已启用该服务。我需要识别(一次是用户)哪个用户可以使用ID为4和5的两种服务。

I wrote that query with Mysql:

我用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);

That query works, but, is there a better technical way to write it?

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

The right result is:

正确的结果是:

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

1 个解决方案

#1


3  

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

or

要么

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

#1


3  

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

or

要么

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