开发者

Mysql how to flatten a result set

I have a stored procedure that will return a list of ids. I want to return that list as a comma separated string, i.e. "1,2,3,4,5".

I know开发者_如何学运维 I can do this using a cursor but is there an easier way to turn a resultset into a flattened string?


MySQL has the group_concat() aggregate function:

SELECT group_concat(some_column) FROM mytable;

Will return all some_column values from table joined by commas.

Caveat: Beware that the result is limited by the group_concat_max_len system variable, which defaults to only 1024 bytes! To avoid hitting this wall, you should execute this before running the query:

SET SESSION group_concat_max_len = 65536;

Or more, depending on how many results you expect. But this value cannot be larger than max_allowed_packet


select group_concat(id) from table

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat


You should really do formatting in the external code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜