2011-02-10 17 views
2

私は両方のテーブルのすべての行を保持しながら2つのテーブルをマージしたいと思います。 以下の例を参照してください。列 'フルーツ'は両方のテーブルに共通しており、両方のテーブルにフルーツの数を記載したいと思います。また、特定の果物は1つのテーブルに表示されますが、他のテーブルには表示されません。 誰も助けることができますか?ありがとう。MySQL - すべての行を保持する2つのテーブルをマージする

TABLE1     TABLE2     
fruit, number    fruit, number   
-------------    -------------   
apples, 1    apples, 10   
pears, 2    oranges, 30   


MERGED TABLE (this is the result I'm after: 
fruit, number_table1, number_table2 
-------------------------------------- 
apples,  1,  10 
pears,  2,  - 
oranges, -,  30 

そして、ここであなたはそれを試してみる必要がある場合は、テーブルを作成するためのコードです....

CREATE TABLE table1 (fruit CHAR(10) NOT NULL, number INT(10) NOT NULL); 
CREATE TABLE table2 (fruit CHAR(10) NOT NULL, number INT(10) NOT NULL); 
insert into table1 (fruit, number) values ('apples', 1), ('pears', 2); 
insert into table2 (fruit, number) values ('apples', 10), ('oranges', 30); 

答えて

0

UNIONを使用してソリューションです:

(select table1.fruit fruit, table1.number number1, table2.number number2 from table1 left join table2 using (fruit)) union (select table2.fruit fruit, table1.number number1, table2.number number2 from table2 left join table1 using (fruit)); 
2

MySQLはFULL OUTER JOINを持っていないので、あなたはそれをするのでエミュレートすることができますUNIONを使用してMySQL 4:ここで

SELECT t1.fruit, t1.number, t2.number 
FROM Table1 AS t1 
LEFT JOIN Table2 AS t2 ON t2.fruit = t1.fruit 
UNION 
SELECT t2.fruit, t1.number, t2.number 
FROM Table1 AS t1 
RIGHT JOIN Table2 AS t2 ON t2.fruit = t1.fruit 
+0

これはうまくいきません。出力は... リンゴ、1、10; ナシ、2、NULL; NULL、NULL、30; – spiderplant0

+0

@ spiderplant0:あなたは正しいです。私は今それを修正しました。右結合のために、2番目の選択はtable1ではなく、table2から "fruit"列を取る必要があります。 – nybbler

0
insert into mergetable 
    (fruit, number_table1, number_table2) 
    select t1.fruit, t1.number, t2.number 
     from table1 t1 
      left join table2 t2 
       on t1.fruit = t2.fruit 
    union 
    select t2.fruit, t1.number, t2.number 
     from table2 t2 
      left join table1 t1 
       on t2.fruit = t1.fruit 
関連する問題