Select all rows that have the tag X and Y for filter results
Here I have a problem that seems to be easy to solve but I can't find the solution. I need to select all rows that have the tag X and Y in 开发者_开发问答the table tags grouped by product.
Tags
+---------+------+
| product | tag |
+---------+------+
| 1 | x |
+--+--+
| 1 | y |
+--+--+
| 2 | y |
+--+--+
| 2 | z |
+--+--+
| 3 | x |
+--+--+
| 3 | y |
+--+--+
So, in this case the rows to be selected are for the product 1 and 3 becasuse both have the tag X and Y
Thanks to all for your help!
SELECT product
FROM tags
WHERE tag IN ('x', 'y')
GROUP BY product
HAVING COUNT(*) = 2
I would use something similar to this...
SET @tags := 'X,Y';
SELECT product, tag
FROM tags
GROUP BY product
HAVING GROUP_CONCAT(DISTINCT tag ORDER BY tag SEPARATOR ',') = @tags;
精彩评论