2010-12-04 53 views
0

我有一個查詢,看起來像這樣:有,如果custom_error的default_error的價值MySQL:如何從另一列中選擇一個列的值,具體取決於哪些列是空的?

SELECT id, description, default_error, custom_error FROM `table1`; 

這給了我

(int) (Text)  (Varchar)   (Varchar) 
id Description Default_Error  custom_error 
--------------------------------------------------- 
1 Hello  Error 123    
2 World  Error 456   This is a custom Error 

我想選擇一個額外的列(「錯誤」)是EMPTY,如果custom_error不是EMPTY,則爲custom_error的值。

任何想法如何在MySQL中做到這一點?

回答

1

嘗試

SELECT id, description, default_error, custom_error, 
    IF(custom_error='', default_error, custom_error) as error 
FROM `table1`; 

- 如果custom_error是NULL默認

SELECT id, description, default_error, custom_error, 
    ISNULL(custom_error, default_error) as error 
FROM `table1`; 
2

如果custom_error是空空的時候比你可以使用這個:

select id, description, coalesce(custom_error, default_error) 
0
SELECT id, description, default_error, custom_error, 
    IF(custom_error='', default_error, custom_error) as error 
FROM `table1`; 
相關問題