几天前,有人帮我解决了这个问题。我正在尝试获取我的数据库的前10条记录。问题是要点。当我在点数字段上使用SUM时,如果同一个用户有超过1条记录,我会得到实际值的两倍...你知道我做错了什么吗? 谢谢
这是只返回用户的第一条记录的代码(不会同一个用户的所有点)
SELECT *
FROM commerce
LEFT JOIN points ON points.id_com = commerce.id
LEFT JOIN comments ON comments.id_com = commerce.id AND (comments.validbycom = 1 AND comments.validbyus = 1)
LEFT JOIN winners ON winners.id_com = commerce.id
GROUP BY commerce.id
ORDER BY SUM(points) DESC, COUNT(comments.id_com) DESC, commerce.date ASC, COUNT(winners.id_com) DESC LIMIT 10
这是完全返回总数
的两倍的代码SELECT SUM(points)
FROM commerce
LEFT JOIN points ON points.id_com = commerce.id
LEFT JOIN comments ON comments.id_com = commerce.id AND (comments.validbycom = 1 AND comments.validbyus = 1)
LEFT JOIN winners ON winners.id_com = commerce.id
GROUP BY commerce.id
ORDER BY SUM(points) DESC, COUNT(comments.id_com) DESC, commerce.date ASC, COUNT(winners.id_com) DESC LIMIT 10
答案 0 :(得分:1)
据推测,points
列来自points
表。额外的join
正在引入额外的行。因此,在进行连接之前尝试聚合:
SELECT sumpoints, commerce.id
FROM commerce LEFT JOIN
(select id_com, sum(points) as sumpoints
from points
group by id_com
) points
ON points.id_com = commerce.id LEFT JOIN
comments
ON comments.id_com = commerce.id AND (comments.validbycom = 1 AND comments.validbyus = 1) LEFT JOIN
winners
ON winners.id_com = commerce.id
GROUP BY commerce.id
ORDER BY sumpoints DESC, COUNT(comments.id_com) DESC, commerce.date ASC, COUNT(winners.id_com) DESC
LIMIT 10