简体   繁体   English

MySQL:选择仅包含两行并具有特定值的所有行吗?

[英]MySQL: Select all that only have two rows, with specific values?

I would like to grab all the users that ONLY have two roles, which are 1 and 4. 我想抓住所有只有两个角色的用户,分别是1和4。

One user role is stored like this: 一个用户角色的存储方式如下:

user_id role_id
54321   1
54321   4
54322   1
54323   1

How can i make a query, that grabs the user_id 54321, because it Only have two roles and these two are 1 and 4? 我如何进行查询,它抓住了user_id 54321,因为它只有两个角色,而这两个是1和4?

I can use WHERE role_id IN (1, 4) but this will also grab users that have other roles. 我可以使用WHERE role_id IN(1,4),但是这也会抓住具有其他角色的用户。

WHERE role_id IN (1, 4) GROUP BY user_ID HAVING COUNT(DISTINCT role_id) = 2

http://gregorulm.com/relational-division-in-sql-the-easy-way/

This is an example of a set-within-sets query. 这是组内查询的示例。 I like to solve these with group by and having because that is the most general approach: 我喜欢来解决这些group byhaving ,因为这是最一般的方法:

select user_id
from user_roles ur
group by user_id
having sum(role_id = 1) > 0 and
       sum(role_id = 4) > 0 and
       sum(role_id not in (1, 4)) = 0;

The having clause has three conditions. having子句具有三个条件。 The first counts the number of times that role is 1, and the user_id passes if there is at least one such role. 第一个计算该角色为1的次数,如果存在至少一个这样的角色,则user_id通过。 The second does the same for 4. The last checks that there are no other values. 第二个对4做相同的操作。最后一个检查是否没有其他值。

I like this structure because it is flexible. 我喜欢这种结构,因为它很灵活。 If the condition were 1 and 4 and others are allowed, you would just drop the third clause. 如果条件是1和4,并且允许其他条件,则只需删除第三个子句。 If the condition were 1 or 4 and no others, then it would look like: 如果条件是1或4,没有其他条件,则看起来像:

having (sum(role_id = 1) > 0 or
        sum(role_id = 4) > 0
       ) and
       sum(role_id not in (1, 4)) = 0;
SELECT u3.user_id
FROM t u1, t u2, t u3
WHERE u1.role_id = 1 AND u2.role_id = 4
 AND u3.user_id = u1.user_id 
 AND u2.user_id = u1.user_id
GROUP BY u3.user_id HAVING COUNT(u3.role_id) = 2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM