I have a flags_products table like below (many to many relationship between flags and products),
flags_products :
flag_id -- product_id
1 -- 1
2 -- 1
3 -- 1
1 -- 2
2 -- 2
4 -- 2
What is the SQL query to get rows that have both the flags (flag_id’s 1 and 2) associated with a product (product_id)? Obviously:
SELECT *
FROM flags_products
WHERE flag_id = 1
AND flag_id = 2
GROUP BY product_id;
…doesn’t work, and gives an empty set. So what would be the correct query?
The exact approach that you should take will depend on your larger requirements. Here’s one possible solution:
This works as long as you can’t have duplicates. If a product can be flagged twice with the same flag_id then you would need:
In both of these cases you’ll need the
GROUP BYto match your column list. MySQL doesn’t require that in order for the query to run (a flaw IMO, but I’ll save that argument for another time ), but the results won’t be determinable for the columns not in theGROUP BY. You can also use the above to queries as subqueries which you can then join to another table or tables.If you know that it will always be exactly two flags for which you’re looking then you can use EXISTS:
Performance may not be very good though.