【问题标题】:Full Outer Join & Union MySQL完全外连接和联合 MySQL
【发布时间】:2017-06-09 04:24:11
【问题描述】:

我目前必须在两个表(右外+左外)上模拟完全外连接,并使用联合来消除重复项。

我想知道,因为我有很多表要这样做,并且我想最终得到一个表,有没有更好的方法来做到这一点。

这是我目前正在做的:

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

【问题讨论】:

  • 我只是松了一口气,我不必使用这个命名策略:-|
  • 你想完成什么?添加您想要实现的示例数据和结果。
  • 创建表 'table+right' 中的选择是否正确 - 看起来你会在 table1 中没有匹配的 table1.col1、table1.col2、table1.col3 得到空值?
  • @P.Salmon 是的,创建表有效。
  • @SirajulHaq 我想在第一个表末尾的列上追加,然后删除重复项。

标签: mysql join union full-outer-join


【解决方案1】:

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

【讨论】:

  • 我正要回来编辑我的问题!这是我得到的:create table table1+table2as select table1.col1, table1.col2, table2.col2 as 'alias' from table1 left outer join table2 on table1.col1 = table2.col1 union select table1.col1, table1.col2, table2.col2 as 'alias' from table1 right outer join table2 on table1.col1 = table2.col1;
  • 你好,我刚用这个方法试着做表,但是到现在已经花了24小时,还没有完成。每个表大约有 3000 万行。
  • 你知道为什么吗?
  • table1和table2有索引吗?
  • 是的,我在两个表的同一列上都有索引@P.Salmon
猜你喜欢
  • 1970-01-01
  • 2018-04-22
  • 2013-03-11
  • 2015-03-31
  • 2014-09-23
  • 2021-10-12
  • 1970-01-01
  • 2013-12-17
  • 2014-05-29
相关资源
最近更新 更多