查找所有重复的组,其中重复表示包含相同成员的组

时间:2015-04-28 16:43:53

标签: sql postgresql bookshelf.js knex.js

我需要一个SQL查询来查找所有重复的组。副本,我的意思是任何具有相同成员的组。因此,正式问题可以写成:返回包含m个通道的给定集合中的所有channel_ids集合:通道i到m包含相同的成员。我有一个联接表groups_members与列group_id,user_id和users表和组表。谢谢你的帮助。

3 个答案:

答案 0 :(得分:1)

你需要使用WHERE IN子句 - 然后在子查询中使用GROUP BY和HAVING子句(你可以说像HAVING COUNT(*)> 1来查找重复项。)

答案 1 :(得分:1)

感谢。我终于弄明白了。

select array_agg(DISTINCT a.channel_id) as channels, a.members from (select channel_id, array_agg(user_id) as members from users_channels group by channel_id) a JOIN (select channel_id, array_agg(user_id) as members from users_channels group by channel_id) b ON a.members = b.members AND a.channel_id <> b.channel_id group by a.members;

答案 2 :(得分:0)

您可以使用完整联接并查看是否有任何user_id为空,这意味着有一个用户在一个组中但不在另一个组中

select gm1.id, gm2.id from group_members gm1
full join group_members gm2 on gm2.user_id = gm1.user_id
where gm1.id < gm2.id
group by gm1.id, gm2.id
having count(case when gm1.user_id is null 
  or gm2.user_id is null then 1 end) = 0

使用2 not exists子句确保不在其他组的用户列表中的用户不存在的另一种方式。

select g.* from groups g1
join groups g2 on g2.id < g1.id
where not exists (
    select 1 from group_members gm1
    left join group_members gm2 on gm1.user_id = gm2.user_id and gm2.id = g2.id
    where gm1.group_id = g1.id
    and gm2.user_id is null
) and not exists (
    select 1 from group_members gm1
    left join group_members gm2 on gm1.user_id = gm2.user_id and gm2.id = g1.id
    where gm1.group_id = g2.id
    and gm2.user_id is null 
)