2017-01-24 12 views
0

私は現在、2つのテーブル(右外部+左外部)で完全な外部結合をシミュレートする必要があり、結合を使用して重複を取り除く必要があります。完全な外部結合と連合MySQL

私はこれを行うテーブルがたくさんあるので、私は最終的に単一のテーブルで終わりたいと思っていました。これを行うにはより良い方法がありますか?

これは私が現在やっているものです:

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

私はこの名前付けポリシーで作業する必要がないことをご存じですか? – Strawberry

+0

あなたは何をしたいですか?達成したいサンプルデータと結果を追加してください。 –

+0

create table 'table + right'のselectは正しいですか?table1.col1、table1.col2、table1.col3のnullが得られるようですが、table1に一致するものはありませんか? –

答えて

0

をこのクエリ

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

を与えられた最初の2つのテーブル を作成する必要はありませんが、あなた

とまったく同じ結果を返します。
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) 
+0

私はちょうど戻って来て、私の質問を編集しようとしていた! は、ここで私が得たものです: 'としてテーブル' TABLE1 + table2'as 選択table1.col1、table1.col2、table2.col2を作成table1.col1 =表2に外部結合table2のを左TABLE1 から 'エイリアス' 。 COL1 組合 選択table1.col1、table1.col2、table2.col2としてTABLE1 から 'エイリアス' 右外table1.col1 = table2.col1にtable2の参加します。 ' –

+0

ねえ、私はテーブルを作ってみるのにこのメソッドを使いましたが、これまでに24時間かかっていますが、まだ完了していません。 各テーブルには約3,000万行があります。 –

+0

理由が分かりますか? –