Home > Back-end >  MySQL - Convert single column into an array
MySQL - Convert single column into an array

Time:09-27

I have a column of data, e.g. as follows:

select league_id from leagues

This gives me a single column (league_id) and 100 rows for that column.

I want to convert it into a single cell (1 row, 1 column) with the following structure:

[1001, 1002, 42022, 203412,  24252, etc..]

Essentially converting the rows into one big array.

There must be a way of doing it but can't see how.

I'm using MariaDB 10.2.

CodePudding user response:

You can use the GROUP_CONCAT() function for that.

Usage is straightforward:

id val
1 1001
2 1002
3 42022
4 203412
5 24252
SELECT group_concat(val) 
  FROM tab

gives you

group_concat(val)
1001,1002,42022,203412,24252

See db<>fiddle.

(Note: Before MariaDB 10.3.3 you cannot use the LIMIT clause with GROUP_CONCAT, in case you should need that).

  • Related