2013-08-28 70 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;