I'm having a problem with fetching some data.
The tables I have (for testing purposes):
Products:
product_id | product_name ----------------------------- 1 | product 1 2 | product 2 3 | product 3
Attributes:
product_id | attribute_id | attribute_value ------------------------------------------------------- 1 | 1 | lorem 1 | 2 | ipsum 2 | 1 | lorem 2 | 2 | doler 3 | 1 | sit 3 | 2 | ipsum
I want to find the products that have lorem stored in attribute_id 1 AND ipsum stored in attribute_id 2.
If I use this query,
SELECT attributes.attribute_id, attributes.attribute_value, products.product_id FROM products Inner Join attributes ON products.product_id = attributes.product_id WHERE (attributes.attribute_id = 1 AND attributes.attribute_value = 'lorem') OR (attributes.attribute_id = 2 AND attributes.attribute_value = 'ipsum')
I get:
attribute_id | attribute_value | product_id ---------------------------------------------------------- 1 | lorem | 1 2 | ipsum | 1 1 | lorem | 2 2 | lorem | 3
But I really want to get this result:
attribute_id_1 | attribute_id_2 | attribute_value_1 | attribute_value_2 | product_id ---------------------------------------------------------- 1 | 2 | lorem | ipsum | 1
Or just product_id 1 as a result.
I can get it working with the next query, but in production (with a lot of data and a few more joins) this is WAY to slow.
SELECT products.product_id FROM products Inner Join attributes ON products.product_id = attributes.product_id WHERE attributes.attribute_value = 'ipsum' AND products.product_id IN ( SELECT products.product_id FROM products Inner Join attributes ON products.product_id = attributes.product_id WHERE attributes.attribute_value = 'lorem' )
I hope you understand what I'm trying to do.
Can someone please help me?
Thanks!