2012-07-21 93 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