这是一个旧线程,但我花了几个小时试图解决同样的问题。
我的查询有两个连接,一个过滤器和一个 SUM 函数。我不是 SQL 专家,但这帮助我实现了即使连接表没有要求和的行仍然显示结果的预期结果。
对我来说,即使总和为零也能显示结果的关键是 GROUP BY。我仍然不是 100% 确定为什么。
根据这篇文章选择了两种类型的连接 - MySQL Multiple Joins in one query?
SELECT registrations.reg_active, registrations.team_id, registrations.area_id, registrations.option_id, registrations.reg_fund_goal, registrations.reg_type, registrations.reg_fee_paid, registrations.reg_has_avatar, users.user_name, users.user_email, users.user_phone, users.user_zip, users.user_age, users.user_gender, users.user_active, SUM(IFNULL(donations.donation_amount,0)) as amt from registrations
INNER JOIN `users`
ON registrations.user_id = users.user_id
AND registrations.event_id = :event_id
LEFT OUTER JOIN `donations`
ON registrations.reg_id = donations.reg_id
GROUP BY donations.reg_id
ORDER BY users.user_name ASC