使用多个连接时,Mysql sum查询返回不正确的结果

时间:2017-04-26 05:33:12

标签: mysql sql

我的查询返回2个子表中2列不正确的总和,我通过谷歌搜索并查看了stackoverflow上的建议,但它们从未起作用。

   si_invoices
   -----------------------------
   id, date
   1, 2014-05-07


   si_invoice_items
   -----------------------------
   id, invoice_id, date , total
   1, 100, 2014-05-07, 200
   2, 100, 2014-05-07, 200

   si_payment
   -----------------------------
   id, ac_inv_id, date , payment
   1, 100, 2014-05-07, 100
   2, 100, 2014-05-07, 200

   SELECT  SI.*,SUM(SII.total) as total,SUM(SIP.payment) as payment FROM 
        (SELECT * FROM si_invoices GROUP BY si_invoices.id) AS SI
     LEFT JOIN si_invoice_items SII ON SII.invoice_id = SI.id
     LEFT JOIN si_payment SIP ON SIP.ac_inv_id = SII.invoice_id
   GROUP BY SI.id

它应该返回400总额的字段'总计'在sql中它返回800并且与' payment'相同。你能指出我的查询中的错误是什么吗?请帮助,赞赏。

由于 M.S

2 个答案:

答案 0 :(得分:2)

直接使用总计,因为您的联接可能会创建您想要的更多行组合。

尝试以下方法:

SELECT id, MAX(Total) as FinalTotal ,MAX(Payment) as FinalPayment
FROM si_invoices a 
    left join 
    (select invoice_id, sum(total) as Total from si_invoice_items group by invoice_id) b 
    on a.id = b.invoice_id
    left join
    (select ac_inv_id, sum(payment) as Payment from si_payment group by ac_inv_id) c 
    on c.ac_inv_id = a.id 
group by id

或者如果id是唯一的:

    SELECT *
FROM si_invoices a 
    left join 
    (select invoice_id, sum(total) as Total from si_invoice_items group by invoice_id) b 
    on a.id = b.invoice_id
    left join
    (select ac_inv_id, sum(payment) as Payment from si_payment group by ac_inv_id) c 
    on c.ac_inv_id = a.id

答案 1 :(得分:0)

详细结果:

select a.invoice,ac_inv_id,sum(a.total),sum(b.payment) from
(select 1 as id, 100 as invoice, '2014-05-07' as date, 200 as total union all
select  2, 100, '2014-05-07', 200) as a
left join
(select 1 as id, 100 as ac_inv_id, '2014-05-07' as date, 100 as payment union all
select 2, 100, 2014-05-07, 200) as b
on a.id = b.id

最终查询:

select a.invoice,ac_inv_id,sum(a.total),sum(b.payment) from
(select * from si_invoice_items) as a
left join
(select * from si_payment) as b
on a.id = b.id

结果:

100 100 400 300