假设我有以下设置
---Posts---
|id
|Title
-----------
---Comments---
|id
|postid
|comment
-----------
一些模拟数据
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
我想从帖子表中返回标题,并通过评论表中的 id 返回与其相关的所有评论。
类似的东西。
Title Comment
Hello World comment1
Good Bye comment2
comment3
Pepsi null
仅使用 SQL 可以吗?
最佳答案
Select Title,
(SELECT GROUP_CONCAT(Comment) FROM Comments
WHERE
Comments.postid=posts.posts) as comments
FROM posts
关于SQL 将一个表的聚合结果作为查询中的一列返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4439129/