简体   繁体   English

MySQL 两个(几乎)相同的表合并值和默认唯一值

[英]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 ID acc_id acc_id name名称 aug_amount aug_amount
1 1个 123 123 name1姓名1 100 100
2 2个 456 456 name2名字2 200 200
3 3个 333 333 name3名字3 300 300

Table2:

id ID acc_id acc_id name名称 sep_amount sep_amount
1 1个 123 123 name1姓名1 200 200
2 2个 456 456 name2名字2 300 300
3 3个 444 444 name4姓名4 400 400

Merged table:

acc_id acc_id name名称 aug_amount aug_amount sep_amount sep_amount
123 123 name1姓名1 100 100 200 200
456 456 name2名字2 200 200 300 300
333 333 name3名字3 300 300 0 0
444 444 name4姓名4 0 0 400 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 acc_id name名称 aug_amount aug_amount sep_amount sep_amount
123 123 name1姓名1 100 100 200 200
456 456 name2名字2 200 200 300 300
333 333 name3名字3 300 300 0 0
444 444 name4姓名4 0 0 400 400

View on DB Fiddle在 DB Fiddle 上查看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM