tags:

views:

67

answers:

3

Hi, 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!

+3  A: 
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
Andrew Bezzub
I've updated query, now it should work as needed
Andrew Bezzub
got it working thanks. Should have thought of that.
Jean-Philippe
A: 

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)
Luke
the dumb answer to a dumb question, I know. Should've thought of that.
Jean-Philippe
+2  A: 
Gaby
Needs to be `HAVING COUNT(DISTINCT c.id) >= 2`, otherwise if there were a client with two associations to category 1 - this would be a false positive. Assuming the data model allows such a thing to happen (probably shouldn't).
OMG Ponies
@OMG, i assumed a logical model :) but you are correct. That would be the all-encompassing choice..
Gaby
+1: Me too Gaby
OMG Ponies