MySQL 中的聚合函数 - 列表(如 Oracle 中的 LISTAGG)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9456380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Aggregate function in MySQL - list (like LISTAGG in Oracle)
提问by Kamil
I need function, that returns list of strings.
我需要函数,它返回字符串列表。
I have data in table like this:
我在表中有这样的数据:
Id MyString
------------------------
1 First
2 Second
3 Third
4 Fourth
I need function like this (something like this works in oracle):
我需要这样的功能(这样的东西在 oracle 中有效):
select LISTAGG(MyString, ', ') as myList where id < 4
That returns something like this:
这将返回如下内容:
myList
------------------------
First, Second, Third
Any ideas?
有任何想法吗?
回答by Mosty Mostacho
You're looking for GROUP_CONCAT()
您正在寻找GROUP_CONCAT()
Try this:
尝试这个:
select group_concat(MyString separator ', ') as myList from table
where id < 4
Of course, you can group by
the results.
当然,你可以group by
得到结果。
回答by alumarcu
As of MySQL 5.7.22 you can also use two JSON aggregation functions: JSON_ARRAYAGGor JSON_OBJECTAGG. You can combine these together with MySQL's JSON functionsto get results aggregated as JSON. Unlike GROUP_CONCAT
, there is no MySQL configuration parameter which would limit the size of the returned value, other than max_allowed_packet
(which affects all queries).
从 MySQL 5.7.22 开始,您还可以使用两个 JSON 聚合函数:JSON_ARRAYAGG或JSON_OBJECTAGG。您可以将这些与MySQL 的 JSON 函数结合在一起,以获得聚合为 JSON 的结果。与 不同GROUP_CONCAT
,除了max_allowed_packet
(影响所有查询)之外,没有 MySQL 配置参数会限制返回值的大小。