2013-08-28 28 views
0

我正在尝试在我的网站上构建评论系统,但是在正确订购注释时遇到了问题。这是我收到了错误的截图:添加连接时出现奇怪的结果顺序

enter image description here

这是查询前出了问题:

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; 

我现在得到这个订单,这是奇怪:

enter image description here

我试着在com.comment_id添加GROUP BY子句,但失败了。我无法理解如何添加一个简单的连接可以改变结果的顺序!任何人都可以回到正确的道路上吗?

示例表中的数据和预期的结果

这些都是我用示例数据相关的表:

[网友]

user_id | username 
--------|----------------- 
1  | PaparazzoKid 

[blog_comments]

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 

[ blog_comment_votes]

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 
+0

K,首先要注意的是,你不应该这样做。你必须分别制作文章,评论和投票。然后通过钩住他们的id像(vote_id - > comment_id,comment_id - > article_id)这样的钩表到他们各自的表中。现在,您可能会看到如下内容:(article for article(article_id,article_text),comment(comment_id,comment_text,art​​icle_id)和vote(vote_id,vote_rate,comment_id)。映射如下OneToMany(article-> comments,comment-> votes )希望现在更清楚你 – Takarakaka

+0

@Takarakaka:谢谢你的时间,但不幸的是,我不明白,我希望我做了:( – TheCarver

回答

1

这很难不看你的查询结果的说法,但我的猜测是,这是因为你只父ID排序,而不是说如何订购当两个记录具有相同的父母ID时。尝试更改您的查询看起来像这样:

SELECT 
    com.comment_id, 
    com.parent_id, 
    com.is_reply, 
    com.user_id, 
    com.comment, 
    com.posted, 
    usr.username, 
    COUNT(c.votes) votes 
FROM 
    blog_comments AS com 
LEFT JOIN 
    users AS usr ON com.user_id = usr.user_id 
LEFT JOIN 
    blog_comment_votes c ON com.comment_id = c.comment_id 
WHERE 
    com.article_id = :article_id AND com.moderated = 1 AND com.status = 1 
GROUP BY 
    com.comment_id, 
    com.parent_id, 
    com.is_reply, 
    com.user_id, 
    com.comment, 
    com.posted, 
    usr.username 
ORDER BY 
    com.parent_id DESC, com.comment_id;