我有两个表T1
和T2
,一列C
对两者都是通用的。我需要一个SQL查询,如果C
null
T1
SELECT
,它将从其他表中选择。
我尝试在THEN
子句中编写IF ELSE
语句但没有运行。不知道SQL中是否有Select C, case when c = null Then Select c from T2
from T1
子句。
{{1}}
答案 0 :(得分:5)
更好的是,大多数RDBMS都支持COALESCE
,它允许您检查多个值并返回第一个非空值。
SELECT COALESCE(T1.C, T2.C) AS C
FROM T1
LEFT OUTER JOIN T2 ON T1.[Primary Key] = T2.[Primary Key]
答案 1 :(得分:0)
你似乎需要一个工会
select c from t1
where c is not null
union
select c from t2
where c is not null
现在,您可以在一个结果集中获取C
和T1
中的所有列T2
,但前提是不为空。
当然,如果这太简化了您的问题,您需要使用加入
select coalesce(t1.c,t2.c) as c
from t1
left join t2 on (t2.id = t1.foreign_id)
这假设T2.ID
是主要关键字,与T1
T1.FOREIGN_ID
相关{/ 1}
执行左连接非常重要,否则当T1
中的行也存在时,您只会获得T2
行。
答案 2 :(得分:0)
这是在TransactSQL中吗?
我喜欢第一个答案,但你也可以这样做......
select case t1.C
when null then t2.C
else t1.C
end as [testC]
from t1
inner join t2
on t1.PKID = t2.PKID