简体   繁体   中英

SQL returning aggregated results from one table as a column in a query

Say I have the following setup

---Posts---
|id
|Title
-----------

---Comments---
|id
|postid
|comment
-----------

Some Mock Data

Posts
ID        Title
1         Hello World
2         Good Bye
3         Pepsi

Comments
ID      postid      comment
 1        1         comment 1
 2        2         comment 2
 3        2         comment 3

I want to return back the Title from the Posts table and all the comments related to it via the id in the comments Table.

Something like.

Title           Comment
Hello World     comment1
Good Bye        comment2
                comment3
Pepsi           null

Is this possible just using SQL?

Select Title, 
       (SELECT GROUP_CONCAT(Comment) FROM Comments
         WHERE
         Comments.postid=posts.posts) as comments
FROM posts
 Select Title, Comment
 from Posts p LEFT Join Comments c on c.PostId = p.id
 Order by 1

However Title will be repeated, ie result will be:

 Title           Comment
 ------------------------
 Hello World     comment1
 Good Bye        comment2
 Good Bye        comment3
 Pepsi           null

从帖子中选择posts.title,comments.comment加入posts.id = comments.postid上的评论

可能您正在寻找: GROUP_CONCAT

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM