mysql 合并两个查询结果

  合并两个查询结果

查询结果1:

select date(complete_time) as time,sum(amt) as amount_out
from withdraw
where state=3
group by date(complete_time)




mysql 合并两个查询结果_第1张图片

查询结果2

select date(update_time) as time,sum(transfer_amount) as amount_in
from user_charge
where status=3
group by date(update_time)


mysql 合并两个查询结果_第2张图片

显然,查询结果的time为主键,目的是将两个查询结果合成一个结果。如果在代码中实现,一次便利一个表添加到另外一个表中,效率非常低。那么在Mysql 中实现方式为:

-- 出金 withdraw
select * from 
(
select date(complete_time) as time,sum(amt) as amount_out,0 as amount_in
from withdraw
where state=3
group by date(complete_time)

union all 
-- 入金 
select date(update_time) as time,0 as amount_out,sum(transfer_amount) as amount_in
from user_charge
where status=3
group by date(update_time)
) a
group by time

使用关键词Union all 。注意:两个列表中的字段要一样才可以合并(顺序也要一样)

查询结果:

mysql 合并两个查询结果_第3张图片

你可能感兴趣的:(数据库)