我有一个简单的文章和评论系统,包含以下表格:
文章表:
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 降序排序?
谢谢
最佳答案
嗯,
其实你的预期结果和结果都是错误的。你如何处理你的数据?
预期的结果是错误的,因为任何 SQL 查询都返回一个表作为结果。它不能在一行中包含另一个表。
您的查询返回以下结果:
第一条:好文章
评论:1 - 我喜欢这篇文章
第一条:好文章
评论:2 - 好
第 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;
}
}
}
希望对您有所帮助!
关于php - 如何在 MYSQL 中使用 GROUP BY 连接来自另一个表的子行并仅显示一次主行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14526259/