1

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

文章表:

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 降序排列评论?

谢谢

4

2 回答 2

1

出色地,

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

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

您的查询返回以下结果:


第1条:好文章

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


第1条:好文章

评论:2 - 好一个


第二条:阅读本文

评论:3 - 等待更多


Witch 应该足以让您获得页面的相关数据。

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

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

$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;
        }
    }
}

希望能帮助到你!

于 2013-01-25T17:01:43.413 回答
0

您在评论表中有一对多的关系,所以使用它,并将文章左连接到相应的评论,或者您可以在原始查询上使用 RIGHT JOIN,我相信。

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

或者

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
于 2013-01-25T16:43:52.910 回答