Home > Database > Mysql Tutorial > How to Aggregate Strings into a List in MySQL (Similar to Oracle's LISTAGG)?

How to Aggregate Strings into a List in MySQL (Similar to Oracle's LISTAGG)?

Barbara Streisand
Release: 2024-12-04 14:15:16
Original
481 people have browsed it

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
Copy after login

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template