Selecting against subsets of a list in MySQL

前端 未结 7 1880
谎友^
谎友^ 2021-01-12 07:21

I\'m quite a begginer and I have two tables: \"product\" and \"product attributes\".

Here\'s some imaginary data (the actual stuff involves more tables )

Pr

7条回答
  •  时光说笑
    2021-01-12 07:43

    Based on your insight guys, I optimized it even further and used only 1 COUNT statement like this:

    SELECT * ,COUNT(p.product_id) AS c FROM product_attribute pa 
    LEFT JOIN products p ON pa.product_id = p.product_id AND pa.attribute_id NOT IN ($filter_list)
    GROUP BY pa.product_id
    HAVING c=0
    

    Does it work ? :)

    Edit:
    That code doesn't return the product's name or other fields it might have. This is the correct one:

    SELECT * ,COUNT(pa.product_id ) AS c FROM products p
    LEFT JOIN product_attribute pa ON pa.product_id = p.product_id AND pa.attribute_id NOT IN ($filter)
    GROUP BY p.product_id
    HAVING c=0
    

提交回复
热议问题