我有两张表如下:
表1:
user_id ancestry
--------- ----------
1 England
1 Ireland
2 France
3 Germany
3 Poland
4 England
4 France
4 Germany
5 France
5 Germany
表2:
country
---------
England
Germany
France
我需要编写一个sql查询,它将挑选出所有那些在表格中每个国家都有祖先的用户ID。我该如何实现。
答案 0 :(得分:0)
DISTINCT
可以拥有来自同一国家/地区的多个祖先,则需要 user_id
SELECT user_id
FROM Table1
GROUP BY user_id
HAVING COUNT(DISTINCT ancestry) = (SELECT COUNT(*) FROM Table2)
修改强>
我意识到table1
可以有table2
之外的国家/地区,而不是Ireland
。
因此,您可能需要使用JOIN
来查看存在多少匹配
SELECT T1.user_id
FROM Table1 T1
JOIN Table2 T2
ON T1.ancestry = T2.country
GROUP BY T1.user_id
HAVING COUNT(DISTINCT T1.ancestry) = (SELECT COUNT(*) FROM Table2)