我试图从sql查询中获取结果,该查询将显示属于多个类别的所有产品。
关系表如下所示
category_id product_id
23 72
33 72
43 72
23 32
33 18
因此,例如,我要尝试选择属于category_id 23、33、43的所有product_id。在这种情况下,只有72个。请注意,我正在尝试捕获属于所有ID(而非OR)的产品。所以这个qry不会工作
SELECT * FROM products AS p JOIN prod_to_cat AS pc ON p.products_id=pc.products_id IN(23,33,43)
所以我尝试了
SELECT * FROM products AS p JOIN prod_to_cat AS pc ON p.products_id=pc.products_id WHERE pc.categories_id=23 AND pc.categories_id=33 AND pc.categories_id=43
如果只有一个类别,它会完美地工作,但是一旦变成多个类别,它将不会显示任何结果。
我也在这里寻找解决方案,并发现了一个建议
SELECT * FROM products AS p JOIN prod_to_cat AS pc ON p.products_id=pc.products_id
WHERE exists (select * from prod_to_cat c where c.products_id=p.products_id AND c.categories_id=23)
AND exists (select * from prod_to_cat c where c.products_id=p.products_id AND c.categories_id=33)
AND exists (select * from prod_to_cat c where c.products_id=p.products_id AND c.categories_id=43)
但这似乎会产生重复的结果。
那么正确的方法是什么呢?
最佳答案
如果您只想获取那些必须属于类别(例如6和18)的产品,请尝试以下查询:
SELECT * FROM `prod_to_cat` WHERE `categories_id` IN (6, 18) GROUP BY `products_id` HAVING COUNT(DISTINCT `categories_id`) = 2 ORDER BY `products_id` ASC
关于sql - 选择属于具有多个参数的关系数据库的行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36538566/