MySQL:如果在第二个表中找到匹配的ID并且ADD丢失了

时间:2018-05-15 12:53:02

标签: mysql sql

我有两张相似的表格:

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 |
+----+---------+

我确实尝试过LEFT JOIN,但无法得到我的结果。并且,'因为决赛桌大约是10k行,我不会使用IN子句。

最终预期结果

id 2和id 4也在balance_second表中,所以我想移动到balance_first表OVERWRITING balance_first;

LEFT表中没有

id 10,所以我们添加它

最后,id 1和3仅在balance_first中,所以我们需要在final_result中不受影响

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

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

2 个答案:

答案 0 :(得分:3)

您可以从balance2获取数据并使用UNION添加balancebalance2无法使用的数据。

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 |

See this SQLFiddle

答案 1 :(得分:0)

我有另一个想法。我们可以先加入第二张桌子。然后用第二个表连接第一个表。联盟他们两个都得到了结果。

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;