Reputation: 1789
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?
Upvotes: 0
Views: 61
Reputation: 815
Select Title,
(SELECT GROUP_CONCAT(Comment) FROM Comments
WHERE
Comments.postid=posts.posts) as comments
FROM posts
Upvotes: 1
Reputation: 363
SELECT posts.title, comments.comment FROM posts JOIN comments ON posts.id = comments.postid
Upvotes: 0
Reputation: 25370
Select Title, Comment
from Posts p LEFT Join Comments c on c.PostId = p.id
Order by 1
However Title will be repeated, i.e. result will be:
Title Comment
------------------------
Hello World comment1
Good Bye comment2
Good Bye comment3
Pepsi null
Upvotes: 0