从存在值的表中选择?

时间:2017-05-10 17:08:05

标签: postgresql select join

如果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

2 个答案:

答案 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)