我想合并 2 个表,同时保留两个表中的所有行,就像同时进行左连接和右连接一样。 请参见下面的示例。 “水果”列对两个表都是通用的,我想列出两个表中的水果数量。此外,一种特定的水果可能会出现在一张 table 上,但不会出现在另一张 table 上。 谁能帮忙?谢谢。
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);
最佳答案
由于 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
关于MySQL - 合并 2 个表保留所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4962537/