1

我有一个这样的 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 ...

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

谢谢

4

1 回答 1

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条件中使用的值的数量而变化

于 2013-10-16T10:53:17.277 回答