我有一个像这样的桌面设计
person_id | department
1 | a
1 | b
2 | a
2 | c
3 | b
3 | a
并希望查询返回属于a和b部门的所有person_id。我认为这将是
的内容select person_id from table group by person_id having ....
但无法弄明白。有谁知道我怎么能这样做?
编辑:我发现我可以做到以下几点。但它似乎是一个黑客。
select person_id from table where department='A' or department='B'
group by person_id having count(1) > 1
答案 0 :(得分:4)
SELECT
person_id
FROM
yourTable
WHERE
department = 'a'
OR department = 'b'
GROUP BY
person_id
HAVING
COUNT(DISTINCT department) = 2
注意:只有当一个人可以多次成为同一部门的成员时才需要DISTINCT。
答案 1 :(得分:1)
您还可以使用子查询来实现此目的:
SELECT person_id
FROM table t1
WHERE t1.department = 'a'
AND EXISTS (SELECT 1
FROM table t2
WHERE t2.department = 'b'
AND t1.person_id = t2.person_id`)