I need to get all products from product_attributes table where I have several pairs of attribute id and filter text value.
It is made harder because text is stored as array separated by ;
.
TABLE product_attribute
Fields product_id, attribute_id, text
SELECT pa.product_id FROM product_attribute as pa
WHERE (
(pa.attribute_id = '15' AND pa.text LIKE '%Male%' )
AND
(pa.attribute_id = '12' AND pa.text LIKE '%Cream%' )
)
Obviously this does not work, because attribute_id cant be 12 and 15 same time.
And I cannot use OR here because it will return all products (all male) + (all cream)
and I need only intersection (male cream)
Got answer here. Alternative to Intersect in MySQL
My variant:
SELECT paz.product_id
FROM (
( SELECT product_id FROM oc_product_attribute WHERE attribute_id = '15' AND text LIKE '%male%' )
UNION ALL
( SELECT product_id FROM oc_product_attribute WHERE attribute_id = '12' AND text LIKE '%creme%' )
) paz GROUP BY paz.product_id HAVING COUNT(*)=2
And Gordon Linoff variant^
SELECT pa.product_id
FROM product_attribute pa
GROUP BY pa.product_id
HAVING SUM(pa.attribute_id = '15' AND pa.text LIKE '%Male%') > 0 AND
SUM(pa.attribute_id = '12' AND pa.text LIKE '%Cream%');