MySQL SUM function in multiple joins

前端 未结 2 941
逝去的感伤
逝去的感伤 2021-01-21 10:44

Hi so this is my case I have those tables

Customer {id,name}
Charges {id,amount,customer_id}
Taxes {id,amount,charge_id}

so I want to SUM amoun

2条回答
  •  庸人自扰
    2021-01-21 11:02

    You want to know if you can do this without subqueries. No, you can't.

    If a row in Charges has more than one corresponding row in Taxes, you can't simply join the tables without duplicating Charges rows. Then, as you have discovered, when you sum them up, you'll get multiple copies.

    You need a way to get a virtual table (a subquery) with one row for each Charge.

                        SELECT ch.customer_id,
                               ch.amount amount,
                               tx.tax tax
                          FROM Charges
                          LEFT JOIN (  
                                      SELECT SUM(amount) tax,
                                             charge_id 
                                        FROM Taxes
                                       GROUP BY charge_id
                              ) tx ON ch.id = tx.charge_id
    

    You can then join that subquery to your Customer table to summarize sales by customer.

提交回复
热议问题