Mysql
 sql >> Base de données >  >> RDS >> Mysql

Requête de somme MySQL renvoyant un résultat incorrect lors de l'utilisation de plusieurs jointures

Utilisez les totaux directement car vos jointures créent probablement plus de lignes combinées que vous le souhaitez.

Essayez ce qui suit :

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

ou si l'identifiant est unique :

    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