当存在多个具有相同名称的列时,请选择非空列

时间:2016-02-23 13:15:33

标签: mysql

我有两张桌子abc,def

abc has the following columns  "value","timeStamp"
def has the columns "value","timeStamp"<

现在我想选择

select abc.value as `ABC Value`,def.value as `DEF Value`,if( abc.timeStamp is not null) abc.timeStamp or else def.timeStamp if def.timeStamp is not null' from abc,def;

我怎么能实现这个

2 个答案:

答案 0 :(得分:0)

您可以通过使用CASE表达式来实现此目的:

select abc.value as `ABC Value`,
       def.value as `DEF Value`,
       case when abc.timeStamp is not null then abc.timeStamp else def.timeStamp as `timeStamp`
from abc,def;

我假设你想通过公共列值加入这个表(并创建一个在mysql中不存在的完整外连接,所以你需要两个左连接),所以你应该有一个连接条件(我还将您的隐式连接语法更改为正确的连接语法

select abc.value as `ABC Value`,
       def.value as `DEF Value`,
       case when def.timeStamp is not null then def.timeStamp else abc.timeStamp as `timeStamp`
from abc  
LEFT OUTER JOIN def ON(abc.value = def.value)
UNION
select abc.value as `ABC Value`,
       def.value as `DEF Value`,
       case when abc.timeStamp is not null then abc.timeStamp else def.timeStamp as `timeStamp`
from def 
LEFT OUTER JOIN abc ON(abc.value = def.value)

答案 1 :(得分:0)

使用coalesce()函数获得所需的结果。请注意,如果两个timestamp列都为null,则它将返回null:

select abc.value as `ABC Value`,def.value as `DEF Value`,
       coalesce( abc.timeStamp, def.timeStamp) as ts
from abc,def;