在SQL结果中有条件地设置列值

时间:2010-06-21 13:19:12

标签: mysql

我正在基于多个表的连接创建结果集。为了简单起见,我附上了一张显示我理论布局的图片:

Diagram http://www.liquidarts.net/images/stackoverflow/sql-theo.png

我的结果集通常如下:

table1.value, table2.value, table3.value

但是,如果设置了table3.table4_key,我希望结果集而不是

table1.value, table2.value, table4.value

任何建议都将不胜感激。我正在尝试纯粹在SQL中完成我的所有数据组织,并避免在PHP中粉碎任何程序数据。

解决方案SQL,根据以下答案:

select
 table1.value,
 table2.value,
 COALESCE(table4.value, table3.value)
from table1 join table2 on
 table2.key = table1.key join table3 on
 table3.key = table2.key left join table4 on
 table4.key = table3.table4_key

1 个答案:

答案 0 :(得分:4)

假设table3.table4_key上有LEFT JOIN table4,您可以使用COALESCE来获得所需的结果。

SELECT table1.value, table2.value, COALESCE(table4.value, table3.value)

“返回列表中的第一个非NULL值,如果没有非NULL值,则返回NULL。”