我一直在研究费用跟踪系统。我有三个主要表:'expenses'、'expense_reports'、'payments'。
我这样构建我的数据库:
我为“expense_reports”和“payments”表添加了一个数据透视表,即“expense_report_payment”来处理多对多关系。 'expense_report_payment' 表有 ff 字段:
这是我获取费用和付款总额的查询:
SELECT
IFNULL(SUM(ex.`amount`), 0) AS total_expenses,
IFNULL(SUM(erp.`payment`), 0) AS total_payment
FROM
`expenses` ex
JOIN `expense_reports` er
ON er.`id` = ex.`expense_report_id`
LEFT JOIN `expense_report_payment` erp
ON erp.`expense_report_id` = er.`id`
JOIN `payments` p
ON p.`id` = erp.`payment_id`
AND p.`deleted_at` IS NULL
AND p.`cancelled_at` IS NULL
AND p.`received_at` IS NOT NULL
WHERE ex.`deleted_at` IS NULL
AND er.`deleted_at` IS NULL
AND er.`rejected_at` IS NULL
AND er.`cancelled_at` IS NULL
如果收到付款,我会得到总金额(total_expenses = 100;total_payment = 100)。但是,如果尚未收到付款,则费用和付款的总金额为零。
答案 0 :(得分:2)
LEFT JOIN
表。通常,您还应该将右联接表上的 WHERE
条件移动到 LEFT JOIN
的 ON
子句。试试
SELECT
IFNULL(SUM(ex.`amount`), 0) AS total_expenses,
IFNULL(SUM(erp.`payment`), 0) AS total_payment
FROM
`expenses` ex
LEFT JOIN `expense_reports` er
ON er.`id` = ex.`expense_report_id`
AND er.`deleted_at` IS NULL
AND er.`rejected_at` IS NULL
AND er.`cancelled_at` IS NULL
LEFT JOIN `expense_report_payment` erp
ON erp.`expense_report_id` = er.`id`
LEFT JOIN `payments` p
ON p.`id` = erp.`payment_id`
AND p.`deleted_at` IS NULL
AND p.`cancelled_at` IS NULL
AND p.`received_at` IS NOT NULL
WHERE ex.`deleted_at` IS NULL
答案 1 :(得分:0)
谢谢大家的帮助。我设法通过在 LEFT JOIN 中加入 'expense_report_payment' 和 'payments' 表解决了这个问题。
SELECT
IFNULL(SUM(ex.`amount`), 0) AS total_expenses,
IFNULL(SUM(erp.payment), 0) AS total_payment
FROM
`expenses` ex
JOIN `expense_reports` er
ON er.`id` = ex.`expense_report_id`
AND er.`deleted_at` IS NULL
AND er.`rejected_at` IS NULL
AND er.`cancelled_at` IS NULL
LEFT JOIN
(SELECT
ep.*
FROM
`expense_report_payment` ep
JOIN `payments` p
ON p.`id` = ep.`payment_id`
WHERE p.`received_at` IS NOT NULL
AND p.`deleted_at` IS NULL
AND p.`cancelled_at` IS NULL
) AS erp
ON erp.expense_report_id = er.`id`
WHERE ex.`deleted_at` IS NULL