你能再帮我一下吗?
有2张 table !这里:
Products
ID | Name
1 X Product
2 Y Product
3 Z Product
Filters
ID | Name
1 X Filter
2 Y Filter
3 Z Filter
Product_Filter
Product_ID | Filter_ID
1 1
1 2
2 1
2 2
2 3
3 3
这个数据透视表包含:
X 产品有 X 过滤器和 Y 过滤器
Y 产品有 X 滤镜和 Y 滤镜和 Z 滤镜
Z 产品有 Z 过滤器
我有这个 sql 代码,我可以通过定义 X 过滤器的 ID 来获得 X 和 Y 产品。
SELECT DISTINCT `products`.*
FROM `products`
JOIN `filters` ON `products`.`id` = `filters`.`id`
WHERE `product_filter`.`filter_id` = 1;
如果我想获得仅包含 X Filter 和 Z Filter 的产品怎么办? 像这样放置和子句,但它当然不起作用。:
WHERE `product_filter`.`filter_id` = 1
and 'product_filter'.'filter_id' = 69;
最佳答案
您需要使用 group by 和 having count 同时在单个列上同时匹配 2 个条件
select
p.* from Products p
join Product_Filter pf on pf.Product_ID = p.ID
join Filters f on f.ID = pf.Filter_ID
where pf.filter_id in (1,69)
group by p.ID
having count(*) = 2
关于php - 如何将 'And' 子句放入多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31114046/