2012-07-21 91 views
0

我有一個頁面顯示與類別X相關的所有帖子。我在顯示與每篇帖子相關的評論時遇到問題。使用PHP和MySQL顯示與帖子相關的評論

下面是相關數據庫表:

TABLE 'articles' 
'article_id' 
'title' 
'article' 
'updated' 
'created' 

TABLE 'categories' 
'cat_id' 
'category' 

TABLE 'article2cat' (relates an article to a category using two primary keys) 
article_id 
cat_id 

TABLE 'comments' 
comment_id 
comment 
user 
created 

TABLE 'comment2article' relates a comment to an article using two primary keys) 
comment_id 
article_d 

拉動了文章和評論的SQL查詢:

SELECT articles.article_id, articles.title, articles.article, DATE_FORMAT(articles.created, "%b, %Y") AS date_created, comments.comment_id, comments.user, comments.comment 
FROM articles INNER JOIN article2cat USING (article_id), comments INNER JOIN comment2article USING (comment_id) 
WHERE cat_id=4 
ORDER BY articles.created DESC; 

顯示的文章和評論的代碼是:

<table id="articles-table" cellpadding="0" cellspacing="0"> 
    <?php while ($row = $result->fetch_assoc()) { ?> 
    <tr> 
     <td id="articles-article"> 
      <div id="articles-article-internal"> 
       <?php echo format($row['article']); ?></div> 
     </td> 
    </tr> 
    <tr> 
     <td><?php echo $row['comment']; ?></td> 
    </tr> 
    <tr> 
     <td>&nbsp;</td> 
    </tr> 
    <?php } ?> 
</table> 

問題是,當我嘗試僅回顯評論與某篇文章/文章有關。目前它顯示所有評論,無論他們屬於哪個帖子。

我在StackOverflow上發現了幾個類似的問題,但沒有一個能夠解決我的問題。

回答

0

分別選擇文章和評論。看看你的查詢結果。隨着每個評論你得到所有文章的副本。當評論數量增長時會發生什麼?例如。你有一篇約5000字的文章。當你做你的查詢時,你會得到5000字節的數據。但是如果你的文章有200條評論?您的查詢結果約爲5000 * 200 +所有評論字節。

SELECT comments.* 
FROM comments INNER JOIN comment2article USING (comment_id) 
WHERE comment2article.article_d= ID of article 
ORDER BY comments.created DESC; 
+0

謝謝Alexey。它已經看起來更好了。但是,它不能解決動態顯示與每篇文章相關的評論的問題。在你的例子中,我必須定義評論與之相關的文章ID。但是如果我在同一頁面上有幾篇文章,每篇都有不同的評論集呢? – 2012-07-21 10:41:53