Selecting against subsets of a list in MySQL

前端 未结 7 1883
谎友^
谎友^ 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:46

    Until MySQL supports the EXCEPT query combination,

    SELECT product_id
      FROM attributes
      WHERE product_id NOT IN (
           SELECT product_id
             FROM attributes 
             WHERE attribute_id NOT IN (21, 23, 24)
         )
      GROUP BY product_id
    UNION
    SELECT id 
      FROM products AS p
      LEFT JOIN attributes AS a
        ON p.id = a.product_id
      WHERE a.product_id IS NULL
    

    If you wish to have only the products with all the given attributes, add a HAVING COUNT(*)=n clause to the first outer query, where 'n' is the length of the attribute list.

提交回复
热议问题