SQL Server being used to run this
I'm trying to pull information that could be variable.. Could you please check it and find the error?
SELECT
id = t.id
name = c.name
fav_flavor = ISNULL((SELECT value FROM ce WHERE key='flavor'), '')
fav_color = ISNULL((SELECT value FROM ce WHERE key='color'), '')
FROM
Transaction t
LEFT JOIN Customer ON t.customer_id=c.id
LEFT JOIN CustomerExtra ce ON ce.id=c.id
Of course this is a siplified query to be used in this example, but it has the scense.
So, basically, I'm not able to use that ce table referenced in the JOIN statement to get random values (in this case 'flavor' and 'color') in the main query.
Is there a way to access those values without adding the condition in the last JOIN and having to duplicate that line as many times as I need values from it? or... is it the right way?
SELECT
id = t.id,
name = c.name,
fav_flavor = ce1.value,
fav_color = ce2.value,
cust_other = ce3.value
FROM
Transaction t
LEFT JOIN CustomerExtra ce1 ON ce1.id=c.id AND ce1.key='flavor'
LEFT JOIN CustomerExtra ce2 ON ce2.id=c.id AND ce2.key='color'
LEFT JOIN CustomerExtra ce3 ON ce3.id=c.id AND ce3.key='other'
CustomerExtra
table sounds like it's designed with the EAV anti-pattern which is part of your problem. Generally, EAV should be avoided. In a more normalized design, you'd be able to solve this problem more easily.