如果value_two
中的值null
不存在(或table_two
},我希望默认使用value_two
中的值table_one
。< / p>
我有以下查询格式:
SELECT one.value_one, two.value_two
FROM schema.table_one one
LEFT JOIN schema.table_two two
ON one.id_value = two.id_value and two.other_column = 'other_val'
WHERE one.id_value = 'id_val';
我知道一个选项是选择所有值并在返回以下内容后在客户端处理:
SELECT one.value_one, one.value_two, two.value_two as two_value_two
FROM schema.table_one one
LEFT JOIN schema.table_two two
ON one.id_value = two.id_value and two.other_column = 'other_val'
WHERE one.id_value = 'id_val';
检查two.value_two
是否存在“干净”方式,如果不存在则默认选择one.value_two
答案 0 :(得分:2)
您可以使用COALESCE
功能。
COALESCE
返回非空的第一个参数。
像这样使用:
SELECT COALESCE(two.value_two, one.value_two)
FROM schema.table_one one
LEFT JOIN schema.table_two two ON one.id_value = two.id_value and two.other_column = 'other_val'
WHERE one.id_value = 'id_val';
请注意COALESCE
是一个ANSI SQL函数,因此可用于SQL的所有实现(MySQL,MS SQL Server,...)
答案 1 :(得分:1)