SQL查询从两个表中选择数据

时间:2016-02-21 23:34:32

标签: mysql

我有两张表如下:

表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。我该如何实现。

1 个答案:

答案 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)