Search code examples
mysqlsqlmany-to-manyentity-attribute-value

select field when a defining condition in separate rows in same table


Input data

I have many-to-many junction table. And I need select product_id when it satisfies several conditions.

SELECT product_id  FROM product_attribute WHERE `value`= '15' AND `value` = 'asus'

I expect get product_id = 1 but query don't return anything. How to solve it? Thanks in advance


Solution

  • Since one record can not be 15 abd asus at the same time you need to group the data and check of both conditions are met for the group

    SELECT product_id 
    FROM product_attribute 
    WHERE `value`= '15' 
       OR `value` = 'asus'
    GROUP BY product_id
    HAVING COUNT(distinct value) = 2