我正在尝试在我的网站上构建评论系统,但在正确排序评论时遇到问题。这是我出错之前的截图:
这是出错之前的查询:
SELECT
com.comment_id,
com.parent_id,
com.is_reply,
com.user_id,
com.comment,
com.posted,
usr.username
FROM
blog_comments AS com
LEFT JOIN
users AS usr ON com.user_id = usr.user_id
WHERE
com.article_id = :article_id AND com.moderated = 1 AND com.status = 1
ORDER BY
com.parent_id DESC;
我现在想blog_comment_votes
使用 LEFT OUTER JOIN 将每个评论的投票包括在我的表中,并提出了这个查询,它有效,但结果的顺序很混乱:
SELECT
com.comment_id,
com.parent_id,
com.is_reply,
com.user_id,
com.comment,
com.posted,
usr.username,
IFNULL(c.cnt,0) votes
FROM
blog_comments AS com
LEFT JOIN
users AS usr ON com.user_id = usr.user_id
LEFT OUTER JOIN (
SELECT comment_id, COUNT(vote_id) as cnt
FROM blog_comment_votes
GROUP BY comment_id) c
ON com.comment_id = c.comment_id
WHERE
com.article_id = :article_id AND com.moderated = 1 AND com.status = 1
ORDER BY
com.parent_id DESC;
我现在得到这个订单,这很奇怪:
我尝试添加一个 GROUP BY 子句,com.comment_id
但也失败了。我不明白添加一个简单的连接如何改变结果的顺序!有人可以帮助回到正确的道路吗?
示例表数据和预期结果
这些是我的相关表格,其中包含示例数据:
[用户]
user_id | username
--------|-----------------
1 | PaparazzoKid
[博客评论]
comment_id | parent_id | is_reply | article_id | user_id | comment
-----------|-----------|----------|------------|---------|---------------------------
1 | 1 | | 1 | 1 | First comment
2 | 2 | 1 | 1 | 20 | Reply to first comment
3 | 3 | | 1 | 391 | Second comment
[博客评论投票]
vote_id | comment_id | article_id | user_id
--------|------------|------------|--------------
1 | 2 | 1 | 233
2 | 2 | 1 | 122
所以顺序应该是
First comment
Reply to first comment +2
Second Comment