MySQL SELECT statement that groups results by identifier?

I am trying to create a MySQL SELECT statement that will select a group of rows from a table and group the results by row id (multiple rows will have the same id).

Here is an example of what I'm trying to do. Let's say I have the following table:

id     |     name  
1      |     Art  
1      |     Arnold  
1      |     Anatoly  
2      |     Beatrice  
2      |     Bertha  
2      |     Betty  
3      |     Constantine  
3      |     Cramer  

I would like MySQL to return data grouped by id as follows:

[1] => Art, Arnold, Anatoly
[2] => Beatrice, Bertha, Betty
[3] => Constantine, Cramer

I know I could make a simple SQL choice and then iterate over the result in PHP, but I would like to let MySQL handle grouping if possible.

+3
source share
1 answer

MySQL GROUP_CONCAT (expr).

SELECT
  GROUP_CONCAT(name)
FROM
  foo
GROUP BY
  id

:

, group_concat_max_len, 1024.
+4

Source: https://habr.com/ru/post/1742895/


All Articles