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)
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.