MySQL查询 - 从三个不同的表中获取总和

时间:2013-07-29 04:51:01

标签: mysql sql

我有一个表sRecords包含一些数据和三个不同的表,每个sRecordID(PK)和fees列有多行,

问题是
如何从与sum匹配的所有三个表中获得sRecordID总费用?

其他三个表是cFees,oFees和iFees feessRecordID(FK sRecords.sRecordID)

修改
我已经sRecordID了,所以我认为任何JOIN都不会在这里工作

2 个答案:

答案 0 :(得分:1)

select t.sRecordID,sum(t1.Fees)+sum(t2.Fees)+sum(t3.Fees) `Sum Fees`
from sRecords t
left join cFees t1 on t1.feeid=t.sRecordID
left join oFees t2 on t2.feeid=t.sRecordID
left join iFees t3 on t3.feeid=t.sRecordID
group by t.sRecordID

答案 1 :(得分:0)

SELECT
   sRecords.sRecordID,
   SUM(cFees.fees) + SUM(oFees.fees) + SUM(iFees.fees) as total_fees
FROM sRecords
LEFT JOIN cFees ON sRecords.sRecordID = cfees.sRecordID
LEFT JOIN iFees ON sRecords.sRecordID = ifees.sRecordID
LEFT JOIN oFees ON sRecords.sRecordID = ofees.sRecordID
GROUP BY sRecords.sRecordID