如何在具有多个共同属性的表中执行自然全外连接?

问题描述

MysqL> select * from r;

+------+------+------+
| A    | B    | C    |
| 1    | 2    | 3    |
| 1    | 2    | 4    |
| 2    | 1    | 3    |
| 3    | 1    | 3    |
+------+------+------+

MysqL> select * from s;

+------+------+------+
| A    | B    | D    |
| 1    | 2    | 1    |
| 2    | 1    | 5    |
| 4    | 2    | 1    |
| 3    | 2    | 1    |
+------+------+------+

现在我想执行自然全外连接。我尝试过左外连接和右外连接以及完全外连接,但它们在执行时只采用了 1 个共同元素。

但是这里要怎么做。

问题是要求在表 r 自然全外连接 s 中包含空条目的行数。

解决方法

您可以“链接”左连接以实现对 full join 的非常好的近似:

select *
from (select a,b from r
      union -- on purpose to remove duplicates
      select a,b from s
     ) rs left join
     r
     using (a,b) left join
     s
     using (a,b);

如果 a/b 可以在 NULLr 中有 s 值,这会变得更加棘手。如果是这种情况,请提出一个问题,并提供适当的样本数据和所需的结果。