2017-05-29 82 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