简体   繁体   English

MySQL:选择另一列不同的重复项?

[英]MySQL: Select duplicates where another column is different?

I am already selecting the duplicates using the following query:我已经使用以下查询选择重复项:

SELECT user_id FROM group_memberships GROUP BY `user_id` HAVING COUNT(*) >= 2

But I want to take it a bit further.但我想更进一步。 I want to check the group_id column on the group_memberships table, and only fetch records where user_id is a duplicate but the duplicates have two or more different group_id column values.我要检查的group_id列上group_memberships表,只取记录,其中user_id是重复的,但重复的有两个或两个以上不同的group_id列值。

So essentially only select users that belong to two different groups.所以基本上只选择属于两个不同组的用户。 I have many rows which are for the same group.我有很多行是同一组的。

Example:例子:

user_id        group_id
1              5
1              5
2              5
2              6

Should only return user_id 2 because 1's duplicates are the same group.应该只返回 user_id 2,因为 1 的重复项是同一个组。

Try, sql_fiddle试试, sql_fiddle

SELECT user_id FROM group_memberships 
               GROUP BY `user_id` 
               HAVING COUNT(DISTINCT(group_id)) >= 2

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

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