so I'm wondering how you would write the following query. I've already figured out how to get what I want, but I'm sure it could be done better and my solution is a little bit ... well ... not how it should be :)
So I have 3 tables, the first being "articles" where articles (for a shop) are stored, then shopping "categories", for example menswear, women, pants, shirts etc. and a pivot-table to connect articles to multiple categories. Typical many-to-many relationship.
1) articles (id, name, price, ...)
2) categories (id, name, ...)
3) article_categories (article_id, category_id)
I want to retrieve all articles which are in both the categories with name "menswear" and "pants". Have in mind that the query might be extended to get articles that are in more categories. They should only be returned if they are in all the categories, not only one of them! Right now I managed to get it working using the following query which checks if the count of categories from GROUP BY is the same as the number of categories I have in the WHERE-clause:
SELECT articles.*
FROM articles a, categories c, article_categories ac
WHERE ac.article_id = a.id
AND ac.category_id = c.id
AND (
c.name = 'menswear'
OR c.name = 'pants'
)
GROUP BY a.id
HAVING COUNT( c.id ) =2
So how would you write this query?
Thanks :)