Full Outer Join&联盟MySQL

时间:2017-01-24 11:25:21

标签: mysql join union full-outer-join

我目前不得不在两个表(右外+左外)上模拟一个完整的外连接,并使用一个联合来摆脱重复。

我很想知道,因为我有很多表可以做到这一点,我想最终得到一个表,是否有更好的方法来做到这一点。

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

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`;

1 个答案:

答案 0 :(得分:0)

无需创建前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);

此查询返回与您的结果完全相同的结果

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)