SQL equivalent of IN operator that acts as AND instead of OR?

此生再无相见时 提交于 2019-12-25 07:47:03

问题


Rather than describe, I'll simply show what I'm trying to do. 3 tables in 3NF. product_badges is the join table. (The exists sub-query is necessary.)

SELECT * FROM shop_products WHERE EXISTS ( // this line cannot change
    SELECT * FROM product_badges as pb 
    WHERE pb.product_id=shop_products.id
    AND pb.badge_id IN (1,2,3,4)
);

Now this will return all the products that have a badge_id of 1 OR 2 OR 3 OR 4. What I want is to get only the products that meet ALL those values. I tried to do pb.badge_id=1 AND pb.badge_id=2 etc but this returns nothing -- which makes sense to me now. I also tried doing multiple queries with an INTERSECT but that resulted in an error. I'm guessing multiple queries is the key but UNION is basically the same as IN and I'm not certain how to use a JOIN in this case.


回答1:


Please try the following (assuming exactly 4 different required bagde_id's):

SELECT * FROM shop_products WHERE EXISTS ( // this line cannot change
    SELECT pb.product_id, count(distinct pb.bagde_id) FROM product_badges as pb 
    WHERE pb.product_id=shop_products.id
    AND pb.badge_id IN (1,2,3,4)
    GROUP BY pb.product_id
    HAVING count(distinct pb.bagde_id) = 4
);


来源:https://stackoverflow.com/questions/11585967/sql-equivalent-of-in-operator-that-acts-as-and-instead-of-or

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!