English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How to use GROUP_CONCAT in CONCAT in MySQL?

Firstly, let's create a table.

mysql> create table GroupConcatenateDemo
-> (
-> id int,
-> FirstName varchar100),
-> Score int
-> );

Insert records

Now let's insert some records.

mysql> insert into GroupConcatenateDemo values(1,'John',94);
mysql> insert into GroupConcatenateDemo values(2,'Bob',98);
mysql> insert into GroupConcatenateDemo values(4,'Carol',100);

Check how many records are in the table.

mysql> select *from GroupConcatenateDemo;

This is the output.

+------+-----------+-------+
| id         | FirstName         | Score         |
+------+-----------+-------+
| 1    | John                    | 94    |
| 2    | Bob                     | 98    |
| 3    | Carol                 | 100         |
+------+-----------+-------+
3 rows in set (0.00 sec)

Syntax for using GROUP_CONCAT

Here is the syntax for joining records.

Select column_name1,group_concat(concat(`Column_name2`,'separatorValue',`Column_name3) separator 'separatorValue')
as AliasName yourTableName group by column_name1;

Here is an example.

mysql> SELECT
-> id,group_concat(concat(`FirstName`,':',`score`) separator ',')
-> as FirstNameAndScore from GroupConcatenateDemo group by id;

This is the output that shows that we have successfully concatenated the records.

+------+-------------------+
| id     | FirstNameAndScore     |
+------+-------------------+
| 1    | John:94           |
| 2    | Bob:98            |
| 3    | Carol:100                         |
+------+-------------------+
3 rows in set (0.00 sec)