从mysql中有条件地选择字段

从mysql中有条件地选择字段,mysql,case,Mysql,Case,是否可以使用Select和Case从几个字段中选择一个,具体取决于哪个字段为空 我基本上想为所有记录返回一个值,逻辑如下 Return $Value from FIeldA if not null else from FieldB if not NULL else from FieldC if not Null else '0' 我使用Case/When/Then来比较特定字段的值,但不是比较字段之间值的一种方式,也不确定这是否可行。简短回答,使用: 它将为您提供三个字段FieldA、F

是否可以使用
Select
Case
从几个字段中选择一个,具体取决于哪个字段为空

我基本上想为所有记录返回一个值,逻辑如下

Return $Value from FIeldA if not null 
else from FieldB if not NULL 
else from FieldC if not Null 
else '0'

我使用Case/When/Then来比较特定字段的值,但不是比较字段之间值的一种方式,也不确定这是否可行。

简短回答,使用:

它将为您提供三个字段
FieldA、FieldB、FieldC
中的第一个不可为空的值。如果全部为空,则返回0。这就是你想要做的


长答案,使用
案例
表达。

短答案,使用:

它将为您提供三个字段
FieldA、FieldB、FieldC
中的第一个不可为空的值。如果全部为空,则返回0。这就是你想要做的


长答案,使用
大小写
表达式。

如果要检查多个字段,如果为空,则返回相同的结果0,然后使用
合并
函数。这是一个简单的代码

SELECT COALESCE(filed1, filed2, filed3, 0) as output from table; 
更多信息

如果您想选择归档使用条件,则选择额外选项,然后选择用例。这是演示代码

SELECT CASE 1 WHEN 1 THEN 'this is case one'
WHEN 2 THEN 'this is case two' 
ELSE 'this is not in the case'
END as 'how to execute case statement'; 
更多信息


如果要检查多个字段,如果为空,则返回相同的结果0,然后使用
合并
功能。这是一个简单的代码

SELECT COALESCE(filed1, filed2, filed3, 0) as output from table; 
更多信息

如果您想选择归档使用条件,则选择额外选项,然后选择用例。这是演示代码

SELECT CASE 1 WHEN 1 THEN 'this is case one'
WHEN 2 THEN 'this is case two' 
ELSE 'this is not in the case'
END as 'how to execute case statement'; 
更多信息