我有4张桌子
1. members(id, name, milk_no, ...)
2. collections(id, member_id, amount, date, ...)
3. credit_payment_transaction(id, member_id, amount, date, ...)
4. deductions(id, member_id, amount, date, ...)
我正在尝试为每个成员提供一个返回的查询。
milk_no | totalDeduction | totalStore | totalCollection
结果应仅返回totalDeduction | totalStore | totalCollection
这就是我想出来的
SELECT members.milk_no, memberCollections.totalCollection, stores.totalStore, memberDeductions.totalDeduction
FROM members
LEFT JOIN
(SELECT SUM(amount) AS totalCollection, member_id
FROM collections
GROUP BY member_id) AS memberCollections
ON memberCollections.member_id = members.id
LEFT JOIN
(SELECT SUM(amount) AS totalStore, member_id
FROM credit_payment_transaction
GROUP BY member_id) AS stores
ON stores.member_id = members.id
LEFT JOIN
(SELECT SUM(amount) AS totalDeduction, member_id
FROM deductions
GROUP BY member_id) AS memberDeductions
ON memberDeductions.member_id = members.id
以上查询返回此
此结果的问题是,它包含不需要的数据(具有3个空值的数据)。当我更改为RIGHT JOIN
时,根本不会返回任何结果。
答案 0 :(得分:1)
只需在查询底部添加WHERE子句:
WHERE totalCollection IS NOT NULL OR totalStore IS NOT NULL OR totalDeduction IS NOT NULL
您可以像这样简化查询:
SELECT m.id, SUM(c.amount) AS totalCollection, SUM(cpt.amount) AS totalStore, SUM(d.amount) AS totalDeduction
FROM members m
LEFT JOIN collections c ON m.id = c.member_id
LEFT JOIN credit_payment_transaction cpt ON m.id = cpt.member_id
LEFT JOIN deductions d ON m.id = d.member_id
GROUP BY m.id
HAVING SUM(c.amount) > 0 OR SUM(cpt.amount) > 0 OR SUM(d.amount) > 0
此查询也将消除成员重复