2016-07-06 17 views
1

我想下面的是一些T-SQL語法正確的版本(希望是什麼波紋管是人類可讀)加入的T1,B和C,但只有在爲C JOIN如果c不爲空

select* from table1 
join table2 
on table1.a = table2.a 
and table1.b = table2.b 
and table1.c = 
when table1.c IS NOT NULL THEN table2.c 
when table1.c IS NULL THEN --dont join on column c, just use the other joins 
END 

I tried the syntax below but it doesn't seem to work (any explanation of why this is incorrect is also appreciated) 

select* from table1 
join table2 
on table1.a = table2.a 
and table1.b = table2.b 
and table1.c = 
when table1.c IS NOT NULL THEN table2.c 
when table1.c IS NULL THEN null --this line is just guessing, but it doesnt work 
end 

回答

4
SELECT 
    T1.my_column, 
    T2.my_other_column 
FROM 
    Table1 T1 
INNER JOIN Table2 T2 ON 
    T2.a = T1.a AND 
    T2.b = T1.b AND 
    (T2.c = T1.c OR T1.c IS NULL) 

另外,如果T2.c永遠不能NULL

SELECT 
    T1.my_column, 
    T2.my_other_column 
FROM 
    Table1 T1 
INNER JOIN Table2 T2 ON 
    T2.a = T1.a AND 
    T2.b = T1.b AND 
    T2.c = COALESCE(T1.c, T2.c) 

我喜歡在任何情況下,第一,由於可讀性。

編輯: COALESCE返回第一個非空參數傳遞到函數中。所以,如果T1.cNULL以上,它將返回T2.c。如果T2.c也是NULL那麼它將嘗試評估NULL = NULL,這將是

你可以通過做COALESCE(T2.c, -1) = COALESCE(T1.c, T2.c, -1)來解決這個問題,但是SQL不能很好地使用索引。

如果你想JOIN他們兩個是NULL,那麼你可以使用的比特以上,或者只是拼出每個可能的組合:

(
    (T2.c IS NULL AND T1.c IS NULL) OR 
    T2.c = T1.c 
) 
+0

這個完美的作品,雖然林不知道凝聚在做什麼(我假設如果沒有匹配檢查空?)。作爲後續,我將如何加入t2.c在t1.c他們都爲null?我知道我不能加入null,但這對於我正在處理的異常數據遷移非常有用 –

+1

我已經爲答案添加了一些解釋,而不是試圖將所有內容都納入評論。 –

0

使用此。

select* from table1 
join table2 
on table1.a = table2.a 
and table1.b = table2.b 
and (table1.c is not null or table1.c = table2.c) 
1

一招,通常提供更好的性能

SELECT 
    T1.my_column, 
    T2.my_other_column 
FROM 
    Table1 T1 
JOIN Table2 T2 
    ON T2.a = T1.a 
AND T2.b = T1.b 
AND T2.c = isnull(T1.c, T2.c) 
相關問題