完全外部联接和联合 MySQL

Full Outer Join & Union MySQL

我目前必须在两个 table 上模拟一个完整的外部连接(右外 + 左外),并使用联合来去除重复项。

我想知道,因为我有很多 table 要做这个,我想最后得到一个 table,有没有更好的方法来做这个.

这是我目前正在做的事情:

create table `table+left` as(
select table1.col1, table1.col2, table1.col3, table2.col2 as `alias`
from table1
left outer join table2
on table1.col1 = table2.col1
);

create table `table+right` as(
select table1.col1, table1.col2, table1.col3, table2.col2 as `alias`
from table1
right outer join table2
on table1.col1 = table2.col1
);

create table `table1+table2` as
select * from `table+left`
union
select * from `table+right`;

不需要创建前 2 个表 给出

drop table if exists table1;
drop table if exists table2;
create table table1 (col1 int,col2 int,col3 int);
create table table2 (col1 int,col2 int,col3 int);

insert into table1 values
(1,1,1),(2,2,2);
insert into table2 values
(1,1,1),(3,3,3);

此查询returns与您的

完全相同的结果
MariaDB [sandbox]> drop table if exists `table1+table2`;
Query OK, 0 rows affected (0.12 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> create table `table1+table2` as
    -> select table1.col1, table1.col2, table1.col3, table2.col2 as `alias`
    -> from table1
    -> left outer join table2
    -> on table1.col1 = table2.col1
    -> union
    -> select table1.col1, table1.col2, table1.col3, table2.col2 as `alias`
    -> from table1
    -> right outer join table2
    -> on table1.col1 = table2.col1;
Query OK, 3 rows affected (0.32 sec)
Records: 3  Duplicates: 0  Warnings: 0

MariaDB [sandbox]>
MariaDB [sandbox]> select * from `table1+table2`;
+------+------+------+-------+
| col1 | col2 | col3 | alias |
+------+------+------+-------+
|    1 |    1 |    1 |     1 |
|    2 |    2 |    2 |  NULL |
| NULL | NULL | NULL |     3 |
+------+------+------+-------+
3 rows in set (0.00 sec)