简体   繁体   English

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

[英]How to add condition on multiple-join table

I have those two tables: 我有这两个表:

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

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

Let's say I have those datas: 假设我有这些数据:

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

tl;dr client #1 has category 1, 2, 3 and client #2 has only category 2 tl; dr 客户端#1具有类别1、2、3,而客户端#2仅具有类别2

I am trying to build a query that would allow me to search multiple categories. 我正在尝试建立一个查询,使我可以搜索多个类别。 For example, I would like to search every clients that has at least category 1 and 2 (would return client #1). 例如,我想搜索至少具有类别1和2的每个客户端(将返回客户端#1)。 How can I achieve that? 我该如何实现?

Thanks! 谢谢!

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

This would do the trick 这可以解决问题

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

[update] [更新]

count(c.id) should be count( DISTINCT c.id ) if a category is allowed to be selected for the same client more than once, as OMG Ponies noted in his comment. 如OMG Ponies在其评论中所述,如果允许为同一客户多次选择一个类别,则count(c.id)应该为count( DISTINCT c.id )

the "dumb" answer “愚蠢”的答案

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM