sql >> Database teknologi >  >> RDS >> Mysql

Mysql sum-forespørgsel returnerer forkert resultat ved brug af flere joinforbindelser

Brug totalerne direkte, fordi dine joinforbindelser sandsynligvis skaber flere rækker i kombination, som du ønsker.

Prøv følgende:

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

eller hvis id er unikt:

    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. Brug af MariaDB Audit Plugin til databasesikkerhed

  2. Tilføj kun data til SQLite-databasen én gang og læs flere gange

  3. Kolonne 'mary' findes ikke

  4. Service Broker-forbedringer i SQL Server 2016