mysql 合并两个查询结果

本文介绍如何在MySQL中高效地合并两个查询结果集,通过使用UNION ALL关键字来组合出金和入金的数据,并确保时间字段作为主键进行聚合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  合并两个查询结果

查询结果1:

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




查询结果2

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


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

<span style="font-size:18px;">-- 出金 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</span>

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

查询结果:

评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值