如何在另一个表中连接子行并在MYSQL中使用GROUP BY只显示一次主行?

时间:2013-01-25 16:39:04

标签: php mysql sql database join

我有一个简单的文章和评论系统,包含以下表格:

文章表:

ID | Writer | Text
 1 | Bob    | good article
 2 | Marley | read this

评论表:

ID | Article_ID | Comment
 1 |      1     |  i love this article
 2 |      1     |  good one
 3 |      2     |  waiting for more

我想选择每篇文章及其评论。我使用以下查询:

SELECT * FROM articles LEFT JOIN comments ON articles.ID = comments.Article_id 

预期结果:

Article 1: good article
Comments: 1 - i love this article
          2 - good one

Article 2: read this
Comments: 3 - waiting for more

我得到了什么:

Article 1: good article
Comments: 2 - good one

Article 2: read this
Comments: 3 - waiting for more

那么如何选择每篇文章及其评论,并按ID降序排列文章,其ID的评论也会降序?

谢谢

2 个答案:

答案 0 :(得分:1)

那么,

实际上你的预期结果和结果都是错误的。你如何处理你的数据?

预期的结果是错误的,因为任何SQL查询都会返回一个表作为结果。它不能包含连续的另一个表。

您的查询返回以下结果:


第1条:好文章

评论:1 - 我喜欢这篇文章


第1条:好文章

评论:2 - 好的


第2条:阅读本文

评论:3 - 等待更多


女巫应该足以获得您网页的相关数据。

但我建议将其分解为单独的查询,文章通常包含您不希望在结果中复制的大量数据。

像那样(未经测试的代码):

$articles_sql="SELECT * FROM articles";
$comments_sql="SELECT * FROM comments";

$articles=$db->query($sql).getResults();

$comments=$db->query($sql).getResults();

foreach($articles as &$article){
    $article['comments']=array();
    foreach ($comments as $comment){
        if($article['id']==$commnet['article_id']){
            $article['comments'][]=$comment;
        }
    }
}

希望它有所帮助!

答案 1 :(得分:0)

你在评论表中有一对多的关系,所以请使用它,然后将文章添加到相应的评论中,或者你可以在原始查询中使用RIGHT JOIN,我相信。

SELECT * FROM comments LEFT JOIN articles ON comments.Article_id = articles.ID

OR

SELECT * FROM articles RIGHT JOIN comments ON articles.ID = comments.Article_id

或者我认为甚至

SELECT * FROM articles JOIN comments ON articles.ID = comments.Article_id 

按文章ID命令降序评论ID降序,点击:

ORDER BY articles.ID DESC, comments.ID DESC