如何在SQL中完成此连接?
TABLE1
+----+-----------+-----------+---------+
| ID | FILTER1 | FILTER2 | DATA1 |
| 1 | filter1-A | filter2-A | data1-A |
| 2 | filter1-B | filter2-B | data1-B |
+----+-----------+-----------+---------+
TABLE2
+----+-----------+-----------+---------+
| ID | FILTER1 | FILTER2 | DATA1 |
| 1 | filter1-B | filter2-B | data2-B |
| 2 | filter1-C | filter2-C | data2-C |
+----+-----------+-----------+---------+
结果
+------------+-----------+---------+---------+
| FILTER1 | FILTER2 | DATA1 | DATA2 |
| filter1-A | filter2-A | data1-A | NULL |
| filter1-B | filter2-B | data1-B | data2-B |
| filter1-C | filter2-C | NULL | data2-C |
+------------+-----------+---------+---------+
答案 0 :(得分:4)
SELECT
COALESCE(TABLE1.filter_1, TABLE2.filter_1) AS filter_1,
COALESCE(TABLE1.filter_1, TABLE2.filter_2) AS filter_2,
TABLE1.data1 AS data_1,
TABLE2.data2 AS data_2
FROM
TABLE1
FULL OUTER JOIN
TABLE2
ON TABLE1.filter_1 = TABLE2.filter_1
AND TABLE1.filter_2 = TABLE2.filter_2
FULL OUTER JOIN
保留每个表中的每条记录,无论另一个表中是否匹配。
COALESCE()
(有些使用ISNULL()
)然后可用于扫描缺失/ NULL值以查找第一个非NULL值。
答案 1 :(得分:2)
这称为FULL OUTER JOIN。
SELECT
ISNULL(T1.FILTER1, T2.FILTER1) AS FILTER_1,
ISNULL(T1.FILTER2, T2.FILTER2) AS FILTER_2,
T1.DATA1 AS DATA_1,
T2.DATA1 AS DATA_2
FROM TABLE1 T1
FULL OUTER JOIN TABLE2 T2
ON T1.FILTER1 = T2.FILTER1
AND T1.FILTER2 = T2.FILTER2
答案 2 :(得分:1)
SELECT G.FILTER1, G.FILTER2, T1.DATA1, T2.DATA1 as DATA2 FROM
(SELECT FILTER1, FILTER2
FROM TABLE1
UNION
SELECT FILTER1, FILTER2
FROM TABLE2
GROUP BY FILTER1, FILTER2) as G
LEFT JOIN TABLE1 as T1 ON T1.FILTER1 = G.FILTER1 AND T1.FILTER2 = G.FILTER2
LEFT JOIN TABLE2 as T2 ON T2.FILTER1 = G.FILTER1 AND T2.FILTER2 = G.FILTER2
答案 3 :(得分:1)
您也可以使用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;
我提供此选择。首先,(对我而言)union all
/ group by
的行为与full outer join
相同是很有趣的。更重要的是,如果您开始添加更多表,那么full outer join
方法会变得很麻烦。将此方法扩展到更多表格很容易。