如何在多连接表上添加条件

时间:2010-03-15 20:12:20

标签: sql mysql join

我有两张桌子:

client:
  id (int) #PK
  name (varchar)

client_category:
  id (int) #PK
  client_id (int)
  category (int)

假设我有这些数据:

client: {(1, "JP"), (2, "Simon")}
client_category: {(1, 1, 1), (2, 1, 2), (3, 1, 3), (4,2,2)}

tl; dr 客户#1 有类别1,2,3,客户#2 只有类别2

我正在尝试构建一个允许我搜索多个类别的查询。例如,我想搜索每个至少类别1和2的客户端(将返回客户端#1)。我怎样才能做到这一点?

谢谢!

3 个答案:

答案 0 :(得分:3)

select client.id, client.name
from client
inner join client_category cat1 on client.id = cat1.client_id and cat1.category = 1
inner join client_category cat2 on client.id = cat2.client_id and cat2.category = 2

答案 1 :(得分:2)

这可以解决问题

SELECT
  c.id, 
  c.name
FROM
  client c 
  INNER JOIN client_category cc on c.id = cc.client_id
WHERE
  cc.category in (1,2)
GROUP BY 
  c.id, c.name
HAVING
  count(c.id) >= 2

<强> [更新]

如果允许为同一个客户多次选择一个类别,那么

count(c.id)应为count( DISTINCT c.id ),正如OMG小马在评论中指出的那样。

答案 2 :(得分:0)

“愚蠢”的回答

select c.id
  from client c
 where c.id in (select cc.client_id from client_category cc where cc.id = 1)
   and c.id in (select cc.client_id from client_category cc where cc.id = 2)