SQL请求,同一个表上的内连接?

时间:2013-10-16 10:49:05

标签: mysql sql inner-join

我有一个像这样的SQL表tbl_client_condition:

id_client | id_condition
1         | A
1         | B
1         | C
2         | A
2         | B
3         | A
3         | B
3         | C
3         | D
4         | C
5         | C
5         | D

我希望得到所有具有A,B和C条件的客户。所以在那个例子中我想要客户端1和3。

我不太清楚如何做到这一点,特别是我想要的条件数量没有定义。这适用于2个条件A和B,例如:

SELECT a.id_client
FROM (
SELECT *
FROM tbl_client_condition
WHERE id_condition = A
) AS a
INNER JOIN (
SELECT *
FROM tbl_client_condition
WHERE id_condition = B
) AS b ON a.id_client = b.id_client

但如果我想要10个id_conditions的记录,我不想做10个INNER JOIN ......

我相信必须有一个简单的解决方案。

由于

1 个答案:

答案 0 :(得分:2)

试试这个

SELECT [id_client] FROM table1
WHERE [id_condition] IN ('A','B','C')
GROUP BY [id_client]
HAVING COUNT(distinct [id_condition]) = 3

<强> SQL FIDDLE

此处COUNT(distinct [id_condition]) = 3会根据IN条件

中使用的值的数量而变化