Maybe this will do the job… I am not the greatest with query stuff so maybe someone can confirm or give better answer.
select *, count(*) from client_tags ct
join clients c on c.id = ct.client_id
where ct.tag_id in (select id from tags where tag_name = 'tag1' or tag_name = 'tag2')
group by ct.client_id
having count(*) > 1
Thank you very much, after some further digging, I was able to come up with the following, similar to yours, which seems to be doing exactly what I needed:
SELECT * FROM clients
LEFT JOIN client_tags ON client_id = id_client
LEFT JOIN tags ON tag_id = id_tag
WHERE tag_id IN ('tag1', 'tag2')
GROUP BY client_id
HAVING COUNT(*) = 2
I am passing (‘tag1’, ‘tag2’) and the count value 2 -the number of tags to match- programmatically.
Thanks for the warning. I tested it after your warning once more and it doesn’t return clients who match any two of the tags, it returns only clients who have all three tags.
No. What fixed your query was adding GROUP BY client_id HAVING COUNT(*) = 2.
With that it doesn’t matter whether you use OR or IN. Both work exactly the same. Try it if you don’t believe me: replace IN with OR in your final query. You’ll see the results are the same.