gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:36:04 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com