0

如何完成这个完整的外部连接?

注意:我问的问题与我原来的帖子不同。

表格1

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

表2

+----+-----------+-----------+---------+
| 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()无处不在的电话。有什么方法可以在不诉诸子查询的情况下避免这种情况?

4

1 回答 1

2

我将重申我对这个问题的回答。

如果您在表中没有重复的键值(对)(如在您的示例数据中),那么您可以使用union alland执行此操作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;
于 2013-07-17T00:56:48.107 回答