2017-05-10 60 views
0

如果一個值value_two不存在(或nulltable_two我想要默認值value_twotable_one從存在價值的表中選擇?

我有以下查詢格式:

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

可以使用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中,...)