mysql 两个表的不同值,MySQL 2个不同表中的两个值之和

本文介绍了一种将两个具有相同结构的表格通过UNION ALL操作进行合并,并对合并后的数据按参考ID进行分组求和的方法。这种方法可以确保即使某条记录只存在于其中一个表格中也能被正确地汇总。

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

I have 2 identical tables with identical columns in each one - "quantity" and "reference". The values in these columns are set out as follows:

table_1

reference quantity

TS00001 235

TS00002 400

TS00003 850

...

table_2

reference quantity

TS00001 670

TS00002 210

TS00003 150

...

I need to join the tables and output the sum of the quantity field for each matched reference ID e.g:

reference total_quantity

TS00001 905

TS00002 610

TS00003 1000

...

I've been trying LEFT JOIN and other methods but I'm getting nowhere quickly so if anyone could spare the time to steer me on to the right track I'd be very grateful. Thanks.

解决方案

You need to UNION the two tables:

SELECT reference, SUM(quantity) AS total_quantity

FROM (

SELECT reference, quantity

FROM table_1

UNION ALL

SELECT reference, quantity

FROM table_2) AS t

GROUP BY reference

This way you are guaranteed to get a record for a reference value even if this is contained in only one of the two tables.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值