Mysql 如果有多个同名列,请选择非空列
我有两张桌子Mysql 如果有多个同名列,请选择非空列,mysql,Mysql,我有两张桌子 abc has the following columns "value","timeStamp" def has the columns "value","timeStamp"< 我如何实现这一点您可以使用如下的CASE表达式实现这一点: select abc.value as `ABC Value`, def.value as `DEF Value`, case when abc.timeStamp is not null then abc
abc has the following columns "value","timeStamp"
def has the columns "value","timeStamp"<
我如何实现这一点您可以使用如下的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中不存在的完整外部连接,因此需要两个左连接),因此您应该有一个连接条件(我还将更改隐式连接语法为正确的连接语法)
使用coalesce()函数获得所需的结果。请注意,如果两个时间戳列都为null,则它将返回null:
select abc.value as `ABC Value`,def.value as `DEF Value`,
coalesce( abc.timeStamp, def.timeStamp) as ts
from abc,def;
你应该编辑你的问题,提供样本数据和期望的结果。我不认为你可以在这样的选择中使用if,我很确定你需要使用case语句
if
只能在您正在查找的MySQL中的存储过程/函数中使用case
语法。什么是“期望结果”?按特定顺序从多个列中选择一个非空列。
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)
select abc.value as `ABC Value`,def.value as `DEF Value`,
coalesce( abc.timeStamp, def.timeStamp) as ts
from abc,def;