[英]MySQL two (almost) identical table merge the values and default unique values
I have two almost identical MySQL tables besides a date column, and I would like to merge them with a select query to create a final table displaying both dates.除了日期列之外,我有两个几乎相同的 MySQL 表,我想将它们与 select 查询合并以创建一个显示两个日期的最终表。
If there is a unique acc_id
in one table -> i want to default the amount in the other to 0
.如果一个表中有唯一的
acc_id
-> 我想将另一个表中的金额默认为0
。
Here is an example of what i mean:这是我的意思的一个例子:
Table1:
id ![]() |
acc_id ![]() |
name![]() |
aug_amount ![]() |
---|---|---|---|
1 ![]() |
123 ![]() |
name1![]() |
100 ![]() |
2 ![]() |
456 ![]() |
name2![]() |
200 ![]() |
3 ![]() |
333 ![]() |
name3![]() |
300 ![]() |
Table2:
id ![]() |
acc_id ![]() |
name![]() |
sep_amount ![]() |
---|---|---|---|
1 ![]() |
123 ![]() |
name1![]() |
200 ![]() |
2 ![]() |
456 ![]() |
name2![]() |
300 ![]() |
3 ![]() |
444 ![]() |
name4![]() |
400 ![]() |
Merged table:
acc_id ![]() |
name![]() |
aug_amount ![]() |
sep_amount ![]() |
---|---|---|---|
123 ![]() |
name1![]() |
100 ![]() |
200 ![]() |
456 ![]() |
name2![]() |
200 ![]() |
300 ![]() |
333 ![]() |
name3![]() |
300 ![]() |
0 ![]() |
444 ![]() |
name4![]() |
0 ![]() |
400 ![]() |
Is there a way i can achieve this with a singular SQL query?有没有一种方法可以通过单个 SQL 查询来实现? I've been playing around for a while but i cant seem to crack it.
我已经玩了一段时间了,但我似乎无法破解它。
Help appreciated.帮助表示赞赏。 Thanks for reading.
谢谢阅读。
Ignoring the PK column, here is one solution where we union the two tables and then select from it:忽略 PK 列,这是一个解决方案,我们合并两个表,然后从中合并 select:
select acc_id, name, sum(aug_amount) as aug_amount, sum(sep_amount) as sep_amount
from (
select acc_id, name, aug_amount, 0 as sep_amount
from table1
union
select acc_id, name, 0, sep_amount
from table2
)z
group by acc_id, name
order by name;
acc_id ![]() |
name![]() |
aug_amount ![]() |
sep_amount ![]() |
---|---|---|---|
123 ![]() |
name1![]() |
100 ![]() |
200 ![]() |
456 ![]() |
name2![]() |
200 ![]() |
300 ![]() |
333 ![]() |
name3![]() |
300 ![]() |
0 ![]() |
444 ![]() |
name4![]() |
0 ![]() |
400 ![]() |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.