MySQL获取具有相同id的表的总和

时间:2012-09-12 02:13:42

标签: mysql join sum

我有四张表person,loan,ca,payments

我希望得到所有付款金额和现金预付金额的总和,其金额与从特定日期加入的贷款具有相同的ID。

这是我的代码,但总和计算错误:

SELECT pd.*,
    l.total_loan_amount,
    sum(c.ca_total_amount) AS ctot,
    sum(p.payment_amount)
FROM personal_data pd
LEFT JOIN loans l
    ON pd.id_personal_data = l.id_personal_data
LEFT JOIN ca c
    ON l.id_loan = c.id_loan
LEFT JOIN payments p
    ON l.id_loan = p.id_loan
WHERE l.loan_date = curDate()
    AND (
        c.ca_date = curDate()
        OR c.ca_date IS NULL
        )
    AND (
        p.payment_date = curDate()
        OR p.payment_date IS NULL
        )
GROUP BY pd.id_personal_data

1 个答案:

答案 0 :(得分:1)

执行此操作有时可能会检索无效结果,因为id有时可能会或可能不会出现在其他表格上。

尝试为要检索的每个列使用子查询。

SELECT  pd.*,
        l.total_loan_amount,
        c.totalCA,
        p.totalPayment
FROM    personal_data pd
        LEFT JOIN loans l
            ON pd.id_personal_data = l.id_personal_data
        LEFT JOIN
        (
            SELECT  id_loan, SUM(ca_total_amount) totalCA
            FROM    ca 
        --  WHERE   DATE(ca_date) = DATE(CURDATE()) OR
        --          ca_date IS NULL
            GROUP BY id_loan
        ) c ON l.id_loan = c.id_loan
        LEFT JOIN
        (
            SELECT  id_loan, SUM(payment_amount) totalPayment
            FROM    payments 
        --  WHERE   DATE(payment_date) = DATE(CURDATE()) OR
        --          payment_date IS NULL
            GROUP BY id_loan
        ) p ON l.id_loan = p.id_loan
WHERE DATE(l.loan_date) = DATE(curDate())

我认为dates每次付款和预付现金都无关紧要,因为您正在根据date of loan

查找总计