MySql - Retrieve correct values using COALESCE?

[亡魂溺海] 提交于 2019-12-11 10:22:00

问题


I have an sql fiddle here: http://www.sqlfiddle.com/#!2/fbd48/1

The colors should be red for flower and brown for bear, but it shows red for both.

Not sure if COALESCE fits here, but was in the accepted answer for something similar here: MySQL - Retrieve row value from different table depending on value of row in a table


回答1:


SELECT mem.member_name, g.*
, coalesce(f.flower_color, b.bear_color) as color
from members mem
inner join general g on mem.member_id = g.member_id
left join flowers f on g.gift_item_id = f.flower_id AND g.gift_item = 'flower'
left join bears b on g.gift_item_id = b.bear_id AND g.gift_item = 'bear'
WHERE g.month='june'

There was no way to differentiate a flower from a bear, so I added tests to the joins. This is pretty smelly. you might rethink your schema.




回答2:


It seems to work if you use unique gift item IDs.

http://www.sqlfiddle.com/#!2/c02c8/1



来源:https://stackoverflow.com/questions/10356083/mysql-retrieve-correct-values-using-coalesce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!