Skip to content
Advertisement

MYSQL select and join multiple where AND clauses from the same table

There is a table of products, and a table for product tags.
Trying to select all the products which have all the tags. So when a user refines their search, they only get the products with all the tags.

tag

Initially I tried an OR and IN, but that brought back all the results. Even if they only had 1 of the required tags

So I tried AND which brings back 0 results.

How do I bring back all the products which has multiple tags of Gold and 10oz and Coin?

Advertisement

Answer

Here is an option that relies on condition aggregation and that can handle any number of conditions (just add more conditions to the HAVING clause):

NB: if you need more columns from products, you would need to add them in the SELECT and in the GROUP BY clause (this will not affect the results of the query, since primary key product.id is already part of the non-aggregated columns).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement