Reputation: 2819
In MySQL, how do I select from another table if a foreign key is set?
What I'm trying to do is select Fields.value
if Fields.value_id
isn't set, otherwise select Values.value
from Values
where Value.id
is equal to Fields.value_id
.
My tables:
Fields:
id | value | value_id
Values:
id | value
What's wrong with my code here?
Code:
SELECT CASE
WHEN Field.value_id = NULL OR Field.value_id = ""
THEN Field.value
ELSE
Value.value
FROM values as Value
WHERE (Field.value_id = Value.id)
Upvotes: 0
Views: 1176
Reputation: 1269753
One syntax error is that you are missing the end
in the case
. I also think you want a left join between the tables. My best guess given the available information is this:
SELECT (CASE WHEN f.value_id = NULL OR f.value_id = ''
THEN f.value
ELSE v.value
END)
FROM fields f left join
values v
on f.value_id = v.id;
Upvotes: 2