SQL 将一个表的聚合结果作为查询中的一列返回

标签 sql mysql

假设我有以下设置

---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/

相关文章:

SQL隐式连接到显式连接

sql - 选择给定时间间隔的行

sql - 如果某个程序未在 5 分钟内完成,如何为该程序创建电子邮件警报?

mysql - 将数据从 My Sql 导入到 Sql Server 的最简单方法

MySQL 选择连接空值

php - 查询生成器数字格式 codeigniter

sql - 光标在光标内

mysql - 找不到此 SQL 错误的原因

mysql - 需要访问.digitalocean_password

mysql - MySQL 的大型后台更新