从过滤器中选择产品

时间:2011-12-13 17:31:42

标签: mysql sql-match-all

我的查询有问题:

我有3张桌子: 产品(id,name) 设置(id,name) product_setting(product_id,setting_id)

例如:我想只选择您选择过滤器的产品!

我这样做:

SELECT p. *, s.id as setting
FROM Products p
INNER JOIN product_setting p2 ON (p.id = p2.product_id)
INNER JOIN settings s ON (s.id = p2.setting_id)
WHERE s.id IN (1,2)

但我得到的所有产品都有'设置'id = 1或id = 2。 如何只获得那些具有'设置'(AND)的产品?

谢谢!

2 个答案:

答案 0 :(得分:2)

SELECT p.*, s.id as setting
FROM Products p
INNER JOIN product_setting p2 ON (p.id = p2.product_id)
INNER JOIN settings s ON (s.id = p2.setting_id)
WHERE s.id IN (1,2)
GROUP BY p.id
HAVING COUNT(*)=2; // size of IN()

答案 1 :(得分:0)

这似乎过度杀人但是......

SELECT p. *, s.id as setting
FROM Products p
INNER JOIN product_setting p2 ON (p.id = p2.product_id)
INNER JOIN settings s ON (s.id = p2.setting_id)
INNER JOIN settings s2 ON (s.id = p2.setting_id)
WHERE 
    s.id = 1
    AND s2.id = 2