您好我需要获取与列出的所有groupid匹配的行
SELECT user_id,group_id
FROM group_privilege_details g
WHERE g.group_id in (102,101)
如果任何一个groupid匹配,这将返回我。但是,我需要在列表中提及所有groupid的userid。
答案 0 :(得分:2)
假设您不能拥有重复的user_id / group_id组合:
SELECT user_id,count(group_id)
FROM group_privilege_details g
WHERE g.group_id in (102,101)
GROUP BY user_id
HAVING count(group_id) = 2
答案 1 :(得分:1)
以下是Steven对通用数组的查询的变体:
SELECT user_id
FROM group_privilege_details
WHERE group_id = ANY(my_array)
GROUP BY 1
HAVING count(*) = array_length(my_array, 1)
只要满足这些要求(问题中没有提到),就可以工作:
group_privilege_details
中是唯一的。通用解决方案,无论这些前提条件如何都可以使用
WITH ids AS (SELECT DISTINCT unnest(my_array) group_id)
SELECT g.user_id
FROM (SELECT user_id, group_id FROM group_privilege_details GROUP BY 1,2) g
JOIN ids USING (group_id)
GROUP BY 1
HAVING count(*) = (SELECT count(*) FROM ids)
unnest()为每个基本元素生成一行。 DISTINCT
删除了可能的欺骗行为。子选择对表格也是如此。
此类查询的广泛选项列表:How to filter SQL results in a has-many-through relation
答案 2 :(得分:0)
请找到我的已解决的查询:
select user_id,login_name from user_info where user_id in (
SELECT user_id FROM
group_privilege_details g WHERE g.group_id in
(select group_id from group_privilege_details g,user_info u where u.user_id=g.user_id
and login_name='123')
GROUP BY user_id HAVING count(group_id) = (select count(group_id)
from group_privilege_details g,user_info u where u.user_id=g.user_id
and login_name='123') ) and login_name!='123'