小编典典

SQL串联行查询

sql

说我们有一张表

table posts
+---------+-----------+--------------------------------+
| postId  | title     | status    | bodyText           |
+---------+-----------+--------------------------------+
|   1     | Hello!    | deleted   | A deleted post!    |
|   2     | Hello 2!  | deleted   | Another one!       |
|   3     | New 1     | new       | A new one!         |
|   4     | New 2     | new       | A new one again!   |    

我们可以在SQL中通过发出单个查询而不用在后端代码中循环进行联接来检索跨行的字段的连接吗?

就像是

根据职位从职位组中选择标题;

应该给像这样的结果

+---------+--------------------+
| deleted | Hello!, Hello 2!   |
| new     | New 1, New 2       |

阅读 159

收藏
2021-04-07

共1个答案

小编典典

如果使用MySQL,则可以使用GROUP_CONCAT

SELECT status, GROUP_CONCAT(title)
FROM posts
GROUP BY status
2021-04-07