2013-07-17 55 views
0

如何完成這個完整的外連接?如何在可能的空鍵上執行完整的外連接?

注意:我問的不是我的original post

TABLE1

+----+-----------+-----------+---------+ 
| ID | FILTER1 | FILTER2 | DATA1 | 
| 1 | NULL  | filter2-A | data1-A | 
| 2 | filter1-B | filter2-B | data1-B | 
| 3 | filter1-C | filter2-C | data1-C | 
| 3 | filter1-D | filter2-D | data1-D | 
+----+-----------+-----------+---------+ 

TABLE2

+----+-----------+-----------+---------+ 
| ID | FILTER1 | FILTER2 | DATA2 | 
| 1 | filter1-A | filter2-A | data2-A | 
| 2 | filter1-B | filter2-B | data2-B | 
| 3 | filter1-C | filter2-C | data2-C | 
| 3 | filter1-D | filter2-D | data2-D | 
+----+-----------+-----------+---------+ 

結果

+------------+-----------+---------+---------+ 
| FILTER1 | FILTER2 | DATA1 | DATA2 | 
| NULL  | filter2-A | data1-A | NULL | 
| filter1-A | filter2-A | NULL | data2-A | 
| filter1-B | filter2-B | data1-B | data2-B | 
| filter1-C | filter2-C | data1-C | data2-C | 
| filter1-D | filter2-D | data1-D | data2-D | 
+------------+-----------+---------+---------+ 

有些擔憂:

兩個表實際上分享5個FIL ter字段,我必須對結果進行一些過濾,這意味着我需要參考過濾字段。而且我不想在很多地方撥打非常詳細的COALESCE()ISNULL()。任何方式避免這種情況,而不訴諸於子查詢?

回答

2

我會重複我對這個問題的答案。

如果你沒有在表中重複的鍵值(對)(作爲示例數據),那麼你可以使用union allgroup by做到這一點:

select filter_1, filter_2, max(data_1) as data_1, max(data_2) as data_2 
from ((select filter_1, filter_2, data_1, NULL as data_2 
     from table1 
    ) union all 
     (select filter_1, filter_2, NULL, data_2 
     from table2 
    ) 
    ) t 
group by filter_1, filter_2; 
+0

這是我真正的第一個念頭。謝謝 – mattalxndr

相關問題