【问题标题】:MySQL COUNT can't countMySQL COUNT 无法计数
【发布时间】:2025-12-04 07:50:01
【问题描述】:

嗯,可以,但我不能查询;)

这是我的查询:

SELECT code.id AS codeid, code.title AS codetitle, code.summary AS codesummary, code.author AS codeauthor, code.date, code.challengeid, ratingItems.*, FORMAT((ratingItems.totalPoints / ratingItems.totalVotes), 1) AS rating, code_tags.*, tags.*, users.firstname AS authorname, users.id AS authorid, GROUP_CONCAT(tags.tag SEPARATOR ', ') AS taggroup,
    COUNT(DISTINCT comments.codeid) AS commentcount
FROM (code)
JOIN code_tags ON code_tags.code_id = code.id
JOIN tags ON tags.id = code_tags.tag_id
JOIN users ON users.id = code.author
LEFT JOIN comments ON comments.codeid = code.id
LEFT JOIN ratingItems ON uniqueName = code.id
WHERE `code`.`approved` = 1
GROUP BY code_id
ORDER BY date desc
LIMIT 15 

重要的一行是第二行——我已经缩进的那一行。我要求它计算特定帖子上的 cmets 数量,但它没有返回正确的数字。例如,带有两个 cmets 的东西将返回“1”。两个不同作者的 8 cmets 仍然会返回“1”...

有什么想法吗?

谢谢!

杰克

编辑:忘了说。当我删除 DISTINCT 部分时,来自两位作者的 8 cmets 返回“28”。抱歉,我不是 MySQL 专家,我真的不明白为什么它会返回 :(

【问题讨论】:

    标签: sql mysql count


    【解决方案1】:

    您按code.id 分组,在每个组中您数(DISTINCT comments.codeid),但comments.codeid = code.id 在JOIN 中定义,这就是为什么您总是得到1。

    您需要按 cmets 上的其他字段进行计数...如果有主代理键,这就是 COUNT(comments.commentid) 的方式。

    此外,如果已知每个组中的 cmets 是不同的,那么简单的 COUNT(*) 应该可以工作。

    【讨论】:

    • 太棒了,谢谢 Yacoder - 我现在正在使用 COUNT (DISTINCT comments.id),效果很好:)