我有一个"产品"表:
id | name
---------
1 | nike
2 | adidas
和" FILTERS"表:
id | name
---------
1 | red
2 | blue
和" PRODUCTS_FILTERS"表:
product_id | filter_id
-----------------------
1 | 1
1 | 2
2 | 2
我需要一个只返回filter1
和filter2
产品的SQL查询(在我的示例中为' nike'产品)。
当我运行以下SQL查询时:
select products.* from products
join product_filters on products.id = product_filters.productId
join filters on product_filters.filterId = filters.id
where filters.id = 1 AND filters.id = 2
尽管" nike"产品在filter1
中有filter2
(红色)和PRODUCTS_FILTERS
(蓝色)我没有得到任何结果,因为join
为nike
制作了2个不同的行{1}}产品。
如何修复查询?
答案 0 :(得分:1)
SELECT products.*
FROM products
INNER JOIN products_filters
ON product_filters.productId = products.id
INNER JOIN filters
ON filters.id = product_filters.filterId
AND filters.id in (1,2)
答案 1 :(得分:1)
SELECT p.id, p.name, COUNT(DISTINCT pf.filter_id) AS cnt
FROM products p LEFT JOIN product_filters pf
ON (pf.product_id=p.id)
WHERE pf.filter_id IN (1,2)
GROUP BY p.id
HAVING cnt=2;
导致:
+----+------+-----+
| id | name | cnt |
+----+------+-----+
| 1 | nike | 2 |
+----+------+-----+
PS。非常感谢@Uueerdo帮助纠正我之前的查询。