I have below query;
SELECT * FROM product pr LEFT OUTER JOIN product_field_value pfv ON pfv.product_id = pr.id AND pfv.product_field_id = 64 INNER JOIN product_colour pc ON pc.id = pfv.value
Now, not every product has product_field_value corresponding to the :
ON pfv.product_id = pr.id AND pfv.product_field_id = 64
But those that have corresponding rows in the product_field_value table, should inner join into product_colour also.
But as you imagine, INNER JOIN to product_colour table after a LEFT OUTER JOIN to product_field_value table, filters out those that DOESN’T HAVE product_field_value relation.
So I’ve come up with this solution;
SELECT * FROM product pr
LEFT OUTER JOIN (SELECT colourPfv.name as name,pfv.product_id as productId,pfv.product_field_id as productFieldId FROM product_field_value pfv
              INNER JOIN product_colour colourPfv on pfv.value = colourPfv.id) colourRel ON colourRel.productId = pr.id AND colourRel.productFieldId = 64
And this query returns both those that DOESN’T HAVE corresponding product_field_value and those that HAVE.
But performance for latest query is too slow.
Is there a better way to do this ?
Advertisement
Answer
What if you move the logic to the WHERE clause, is performance better?
SELECT * FROM product pr
LEFT JOIN product_field_value pfv 
    ON pfv.product_id = pr.id AND pfv.product_field_id = 64
LEFT JOIN product_colour pc ON pc.id = pfv.value
WHERE pfv.product_id IS NULL OR (pfv.product_id IS NOT NULL AND pc.id IS NOT NULL)