2017-05-29 81 views
1

我有一个要求有条件地连接两个表。 对于防爆:SQL-有条件的连接

T1 
--Col1 
--Col2 
--Col3 
T2 
--Col1 
--Col2 
--Col3 

加入T1和T2在col1两个表中,如果Col1中为NULL,则两个表加入T1和T2上col2的。 如何做到这一点?

+0

参见COALESCE()。 – Strawberry

+0

标签,请。 MySQL或SQL服务器? – KtX2SkD

+0

我删除了不兼容的数据库标记。 –

回答

1

您可以在join crtieria

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 
+0

如果t1.col1为空而t2.col1不是? – PacoDePaco

+0

@PawełKucharski更新了! – DhruvJoshi

+0

逻辑上正确,但性能可能很差。基于IF语句和两个单独的select语句可能会更好地执行,但这取决于OP。而且它只会检查整个列,这可能不够。 – PacoDePaco

0
SELECT 
* 
FROM 
    T1 INNER JOIN T2 
ON T1.COL1=T2.COL1 OR T1.COL2=T2.COL2 
+0

需要一些解释。 –

0

你的条件不明确使用如下的查询,它使用case条件。如果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第一个条件将失败。

0

我正在使用内联视图。选中此查询。

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; 
0

感谢所有:)

我只TOT下面的查询,让我知道,如果这个工程。

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