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



除了一个日期列之外,我还有两个几乎相同的MySQL表,我想将它们与一个选择查询合并,以创建一个显示两个日期的最终表。

如果在一个表中存在唯一的CCD_ 1;我想将另一个中的金额默认为0

下面是我的意思的一个例子:

Table1:

aug_amount
id acc_id 名称
1 123 名称1 100
2 456 名称2 200
3 333 名称3 300

忽略PK列,这里有一个解决方案,我们将两个表合并,然后从中选择:

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;
>sep_amount
acc_id名称aug_amount
123名称1100200
456名称2200300
333名称33000
444名称40400

最新更新