我有3个mysql表,如下所示:http://pastebin.com/1eH6R3f9
我尝试了这个查询,但它多次myltiplies amout。有人请帮忙!
SELECT
m.merchantID,m.merchantName,SUM(pr.dr_amount) 'Total Due', SUM(me.paidAmount) 'Total Paid'
FROM merchant m
INNER JOIN product_report pr, merchant_payment me
WHERE m.merchantID = pr.merchantID AND m.merchantID = me.merchantID
GROUP BY m.merchantID
答案 0 :(得分:0)
您需要在进行连接之前沿每个维聚合数据。否则,您将获得笛卡尔积:
SELECT m.merchantID, m.merchantName, pr.TotalDue, me.TotalPaid
FROM merchant m LEFT JOIN
(select pr.merchantId, sum(pr.dr_amount) as TotalDue
from product_report pr
group by pr.merchantId
) pr
ON m.merchantId = pr.merchantId LEFT JOIN
(select me.merchantId, sum(me.paidAmount) as TotalPaid
from merchant_payment me
group by me.merchantId
) me
ON m.merchantId = me.merchantId;
另外:
from
子句中使用逗号。