SQL串联行查询 [英] SQL concatenate rows query
本文介绍了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发出单个查询,而不必在后端代码中循环进行联接,从而在SQL中检索跨行的字段的连接吗?
Can we, in SQL, retrieve a concatenation of a field across rows, by issuing a single query, not having to do the join up in a loop in our back-end code?
类似
select title from posts group by status ;
应该给出类似的结果
+---------+--------------------+
| deleted | Hello!, Hello 2! |
| new | New 1, New 2 |
推荐答案
If you use MySQL then you can use GROUP_CONCAT:
SELECT status, GROUP_CONCAT(title)
FROM posts
GROUP BY status
这篇关于SQL串联行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文