我有四个表部门、团队、费用和收入。
出发表:
id depart
团队表:
id name depart_id
费用表:
id team_id expense_type amount date
和收益表:
id team_id earning_type earning_peace date
我想计算离开的总费用金额和总收入和平。我使用这个查询:
SELECT d.id, d.depart,
SUM(if(`earning_type` = 1, earning_peace, 0)) as earning_peace1,
SUM(if(`earning_type` = 2, earning_peace, 0)) as earning_peace2,
SUM(if(`earning_type` = 3, earning_peace, 0)) as earning_peace3,
SUM(if(`earning_type` = 4, earning_peace, 0)) as earning_peace4,
SUM(if(`expense_type` = 1, amount, 0)) as `expense1`,
SUM(if (`expense_type` = 2, amount, 0)) as expense2,
SUM(if (`expense_type` = 3, amount, 0)) as expense3,
SUM(if (`expense_type` = 4, amount, 0)) as expense4
FROM depart d INNER JOIN team m ON d.id = m.depart_id
LEFT JOIN earning e ON m.id = e.team_id
LEFT JOIN expense ex ON ex.team_id = m.id
GROUP BY d.id
但是查询在某些出发时返回总收入的两倍。此查询中的错误有什么帮助?