EN
MySQL - concatenate multiple rows into one field
0 points
In this article, we would like to show you how to concatenate multiple rows into one field in MySQL.
Quick solution:
xxxxxxxxxx
1
SELECT `column1`,
2
GROUP_CONCAT(`column2` SEPARATOR 'separator') AS 'alias_name'
3
FROM `table_name`
4
GROUP BY `column1`;
To show how to combine multiple rows into one field, we will use the following table:

Note:
At the end of this article you can find database preparation SQL queries.
In this example, we want to display all the colors and a list of people who like each color in one field.
Query:
xxxxxxxxxx
1
SELECT `favorite_color`,
2
GROUP_CONCAT(`name` SEPARATOR ', ') AS 'people'
3
FROM `users`
4
GROUP BY `favorite_color`;
Output:

Note:
You can add
DISTINCT
clause to avoid duplicated names:xxxxxxxxxx
1SELECT `favorite_color`,
2GROUP_CONCAT(DISTINCT `name` SEPARATOR ', ') AS 'people'
3FROM `users`
4GROUP BY `favorite_color`;
create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE `users` (
2
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
3
`name` VARCHAR(50) NOT NULL,
4
`favorite_color` VARCHAR(100) NOT NULL,
5
PRIMARY KEY (`id`)
6
);
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO `users`
2
( `name`, `favorite_color`)
3
VALUES
4
('Tom', 'red'),
5
('Chris', 'green'),
6
('Kate', 'blue'),
7
('Jack', 'green'),
8
('Mark', 'green'),
9
('Ann', 'orange'),
10
('Natalie', 'pink');