简体   繁体   English

MySQL:如何根据另一列为空,从另一列中选择具有值的列?

[英]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        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. 我想选择一个额外的列(“错误”),如果custom_error为EMPTY,则具有default_error的值,如果custom_error为NOT EMPTY,则具有custom_error的值。

Any idea how to do this in MySQL? 知道如何在MySQL中执行此操作吗?

如果custom_error为空,则为空,则可以使用以下命令:

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 -如果custom_error默认为NULL

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`;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM