1

如何在 SQL 中完成这种连接?

表格1

+----+-----------+-----------+---------+
| ID | FILTER1   | FILTER2   | DATA1   |
| 1  | filter1-A | filter2-A | data1-A |
| 2  | filter1-B | filter2-B | data1-B |
+----+-----------+-----------+---------+

表2

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

4 回答 4

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() Some use ISNULL())然后可用于扫描缺失/NULL 值以查找第一个非 NULL 值。

于 2013-07-16T22:04:16.527 回答
2

这称为全外连接。

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
于 2013-07-16T22:02:10.010 回答
1

您也可以使用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;

我提供这个作为替代方案。一方面,有趣的是(对我来说)union all/group by可以表现得与full outer join. 更重要的是,如果你开始添加更多的表,那么这种full outer join方法就会变得很麻烦。将此方法扩展到更多表很容易。

于 2013-07-16T23:39:17.290 回答
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
于 2013-07-16T22:18:22.390 回答