简体   繁体   中英

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

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). 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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