我在左联接中查询的总计数错误。

这是2个单独的查询,分别提供正确的结果。

SELECT wallpaper_id FROM `contest_participants` WHERE contest_id=2

SELECT wallpaper_id, SUM(upvotes) FROM `contest_wallpaper_upvote` WHERE contest_id=2 GROUP BY wallpaper_id


我已经使用加入来总结如下的投票

Select distinct p.wallpaper_id, sum(u.upvotes) from contest_participants p
Left join contest_wallpaper_upvote as u
On p.wallpaper_id = u.wallpaper_id
Where p.contest_id = 2  group by p.wallpaper_id


问题是,如果upvote表中没有wallpaper_id的条目,则总数计数错误。

有人可以帮我解决该查询吗?

谢谢

最佳答案

您可以像下面那样检查。如果u.wallpaper_id为null,则可以添加0否则为u.upvotes

Select distinct p.wallpaper_id, sum(if(u.wallpaper_id is null, 0, u.upvotes)) as upvotes from contest_participants p
Left join contest_wallpaper_upvote as u
On p.wallpaper_id = u.wallpaper_id AND u.contest_id = 2
Where p.contest_id = 2  group by p.wallpaper_id

09-25 16:31