MySQL - 合并2个表,保留所有行

时间:2011-02-10 20:51:58

标签: mysql join

我想合并两个表,保持两个表中的所有行,例如同时执行左连接和右连接。 见下面的例子。列'水果'对于两个表都是通用的,我想列出两个表中的水果数量。特定的水果也可能出现在一张桌子中而不是另一张桌子上。 有人可以帮忙吗?感谢。

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 

答案 2 :(得分: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));