Note that there are some explanatory texts on larger screens.

plurals
  1. POSearch for products with multiple criteria
    primarykey
    data
    text
    <p>I'm having a problem with fetching some data.<br> The tables I have (for testing purposes):</p> <p>Products:</p> <pre> product_id | product_name ----------------------------- 1 | product 1 2 | product 2 3 | product 3 </pre> <p>Attributes:</p> <pre> product_id | attribute_id | attribute_value ------------------------------------------------------- 1 | 1 | lorem 1 | 2 | ipsum 2 | 1 | lorem 2 | 2 | doler 3 | 1 | sit 3 | 2 | ipsum </pre> <p>I want to find the products that have lorem stored in attribute_id 1 AND ipsum stored in attribute_id 2.</p> <p>If I use this query,</p> <pre> 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') </pre> <p>I get:</p> <pre> attribute_id | attribute_value | product_id ---------------------------------------------------------- 1 | lorem | 1 2 | ipsum | 1 1 | lorem | 2 2 | lorem | 3 </pre> <p>But I really want to get this result:</p> <pre> attribute_id_1 | attribute_id_2 | attribute_value_1 | attribute_value_2 | product_id ---------------------------------------------------------- 1 | 2 | lorem | ipsum | 1 </pre> <p>Or just product_id 1 as a result.<br></p> <p>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.</p> <pre> 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' ) </pre> <p>I hope you understand what I'm trying to do.<br><br> Can someone please help me?<br> Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload