Home >Database >Mysql Tutorial >How to Aggregate Strings into a List in MySQL (Similar to Oracle's LISTAGG)?
Aggregate Function in MySQL: Aggregate Values into a List (Similar to LISTAGG in Oracle)
Query:
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): select LISTAGG(MyString, ', ') as myList where id < 4 That returns something like this: myList ------------------------ First, Second, Third
Answer:
MySQL provides the GROUP_CONCAT() function for this purpose. It aggregates values into a comma-separated list.
Query Using GROUP_CONCAT():
select group_concat(MyString separator ', ') as myList from table where id < 4
This query will return a list of strings, separated by commas, for all rows where the id is less than 4. The 'myList' column will contain the aggregated result.
Note: The GROUP_CONCAT() function allows for grouping by multiple columns if necessary. For example:
select group_concat(MyString separator ', ') as myList from table where id < 4 group by another_column
This query will group the results by the another_column column and create a list of strings for each group.
The above is the detailed content of How to Aggregate Strings into a List in MySQL (Similar to Oracle's LISTAGG)?. For more information, please follow other related articles on the PHP Chinese website!