MySQL - объединение 2 таблиц с сохранением всех строк - PullRequest
2 голосов
/ 10 февраля 2011

Я хотел бы объединить 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);

Ответы [ 3 ]

2 голосов
/ 10 февраля 2011

Поскольку MySQL не имеет FULL OUTER JOIN, вы можете эмулировать его начиная с MySQL 4, используя UNION:

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 голосов
/ 11 февраля 2011

Вот решение с использованием 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));
0 голосов
/ 10 февраля 2011
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 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...