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

标签 mysql join

我想合并 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/

相关文章:

mysql - 涉及多个 JOIN 的查询困难

PHP MySQL 多重连接

python - Pandas groupby : *full* join result of groupwise operation on original index

mysql - 如何在 MySQL 中加入相同的数据库名称?

mysql - 在 Mysql 中向日期添加天数

mysql - 连接三个 MySQL 表并从一个表中获取最大值

mysql - 连接两个 mysql 查询,按第二个查询的结果对第一个查询进行排序

mysql - 1 天前和 1 周前的行之间的 SQL 差异

php - foreach循环中的mysql更新

mysql - 多个用户同时访问数据库