MySQL: How to select a column with a value from another column, depending on which columns are empty?
I have a query that looks like this:
SELECT id, description, default_error, custom_error FROM `table1`;
Which gives me
(int) (Text) (Varchar) (Varchar)
id Description Default_Error custom_error
---------------------------------------------------
1 Hello 开发者_StackOverflow Error 123
2 World Error 456 This is a custom Error
I'd like to select an extra column ("error") that has the value of default_error if custom_error is EMPTY, and the value of custom_error if custom_error is NOT EMPTY.
Any idea how to do this in MySQL?
If custom_error is null when empty than you can use this:
select id, description, coalesce(custom_error, default_error)
Try
SELECT id, description, default_error, custom_error,
IF(custom_error='', default_error, custom_error) as error
FROM `table1`;
OR - if custom_error is NULL
by default
SELECT id, description, default_error, custom_error,
ISNULL(custom_error, default_error) as error
FROM `table1`;
SELECT id, description, default_error, custom_error,
IF(custom_error='', default_error, custom_error) as error
FROM `table1`;
精彩评论