如何完成这个完整的外连接?
注意:我问的问题不同于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 |
+------------+-----------+---------+---------+
一些担忧:
这两个表实际上共享五个过滤字段,我必须对结果进行一些过滤,这意味着我需要经常引用过滤字段。而且我不希望到处都是非常冗长的COALESCE()
或ISNULL()
。没有求助于子查询的任何方法可以避免这种情况吗?
答案 0 :(得分:2)
我会重复我对这个问题的回答。
如果表格中没有重复的键值(对)(如示例数据中所示),则可以使用union all
和group 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;