SQL条件联接
我需要有条件地连接两个表。 例如: 从两个表中连接Col1上的T1和T2,如果Col1为NULL,则从两个表中连接Col2上的T1和T2。SQL条件联接,sql,Sql,我需要有条件地连接两个表。 例如: 从两个表中连接Col1上的T1和T2,如果Col1为NULL,则从两个表中连接Col2上的T1和T2。 如何实现这一点?您可以使用下面这样的查询,在joincrtieria中使用case条件 select * from t1 join t2 on case when (t1.col1 is NULL or t2.col1 is NULL) then t1.col2 else t1.col1 end = case
如何实现这一点?您可以使用下面这样的查询,在
join
crtieria中使用case
条件
select *
from
t1 join t2
on
case
when (t1.col1 is NULL or t2.col1 is NULL)
then t1.col2
else t1.col1
end
=
case
when (t1.col1 is NULL or t2.col1 is NULL)
then t2.col2
else t2.col1
end
你的条件模棱两可。如果
col1
仅在一个表中NULL
,该怎么办
在任何情况下,您都可以指定如下逻辑:
select . . .
from t1 join
t2
on (t1.col1 = t2.col1) or
( (t1.col1 is null or t2.col1 is null) and t1.col2 = t2.col2)
如果任一列为
NULL
我正在使用内联视图,则第一个条件将失败。检查此查询
select * from
(select t1.col1,t1.col2,t1.col3 from table1 t1)q1,
(select t2.col1,t2.col2,t2.col3 from table1 t2)q2
where t1.col1=t2.col1 or t1.col2=t2.col2;
谢谢大家:)
我只是想了解一下下面的问题,让我知道这是否有效
Select * from
(select col1, col2, col3, coalesce(col1, col2) as join_key)q1,
(select col1, col2, col3, coalesce(col1, col2) as join_key)q1,
where q1.join_key = q2.join_key
请参阅COALESCE().标记。MySQL还是SQL Server?我删除了不兼容的数据库标记。您使用的是哪种数据库标记?如果t1.col1为null,而t2.col1不为null会怎么样?逻辑正确,但性能可能很差。基于IF语句和两个单独的select语句可能会执行得更好,但这取决于OP。而且它只会检查整个列,这可能不够。需要一些解释。
select * from
(select t1.col1,t1.col2,t1.col3 from table1 t1)q1,
(select t2.col1,t2.col2,t2.col3 from table1 t2)q2
where t1.col1=t2.col1 or t1.col2=t2.col2;
Select * from
(select col1, col2, col3, coalesce(col1, col2) as join_key)q1,
(select col1, col2, col3, coalesce(col1, col2) as join_key)q1,
where q1.join_key = q2.join_key