mysql:如果在第二个表中找到匹配的id,如何“覆盖”第一个表中的数据并添加缺少的内容

2lpgd968  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(215)

我有两张类似的table:

balance_first

+----+---------+
| id | balance |
+----+---------+
|  1 |      12 |
|  2 |      50 |
|  3 |       0 |
|  4 |      55 |
+----+---------+

balance_second

+----+---------+
| id | balance |
+----+---------+
|  2 |     7.5 |
|  4 |    2.33 |
| 10 |    1.23 |
+----+---------+

我尝试了左连接,但没有得到结果。因为最后一个表大约是10k行,所以我不会在子句中使用。
最终预期结果
id 2和id 4也在balance\u第二个表中,所以我想移动到balance\u第一个表覆盖balance\u第一个表;
id 10不在左表中,所以我们添加它
最后,id 1和3只在平衡中,所以我们需要在最终结果中保持不变

+----+---------+
| id | balance |
+----+---------+
|  1 |      12 |
|  2 |     7.5 |
|  3 |       0 |
|  4 |    2.33 |
| 10 |    1.23 |
+----+---------+

这是一个sql小提琴:http://sqlfiddle.com/#!9/eabdfe/1号

zujrkrfu

zujrkrfu1#

你可以从 balance2 使用 UNION 添加数据的步骤 balance 在中不可用 balance2 .

SELECT ID, balance FROM balance2
UNION
SELECT b.ID, b.balance FROM balance b
LEFT JOIN balance2 b2 ON b2.ID = b.ID
WHERE b2.ID IS NULL
ORDER BY ID

输出:

| ID | balance |
|----|---------|
|  1 |      12 |
|  2 |     7.5 |
|  3 |       0 |
|  4 |    2.33 |
| 10 |    1.23 |

看到这把小提琴了吗

wqsoz72f

wqsoz72f2#

我有另一个主意。我们可以把第二张table留给第一张。然后把第一个表和第二个表连接起来。把他们两个联合起来以得到结果。

select id,balance
from ((select b2.id as 'id',b2.balance as 'balance'
from balance2 b2
LEFT JOIN balance b 
ON b2.id = b.id)
UNION
(select b.id as 'id',IF(b2.balance is null,b.balance,b2.balance) as 'balance'
from balance b 
LEFT JOIN balance2 b2
ON b.id = b2.id)) derived_table
order by id;

相关问题