Firstly, let us create a table.
mysql> create table GroupConcatenateDemo -> ( -> id int, -> FirstName varchar(100), -> Score int -> ); Query OK, 0 rows affected (0.61 sec)
Inserting records
Let us now insert some records.
mysql> insert into GroupConcatenateDemo values(1,'John',94); Query OK, 1 row affected (0.16 sec) mysql> insert into GroupConcatenateDemo values(2,'Bob',98); Query OK, 1 row affected (0.16 sec) mysql> insert into GroupConcatenateDemo values(4,'Carol',100); Query OK, 1 row affected (0.20 sec)
To check how many records are present in the table.
mysql> select *from GroupConcatenateDemo;
Here is the output.
+------+-----------+-------+ | id | FirstName | Score | +------+-----------+-------+ | 1 | John | 94 | | 2 | Bob | 98 | | 3 | Carol | 100 | +------+-----------+-------+ 3 rows in set (0.00 sec)
Syntax to use GROUP_CONCAT
The following is the syntax to concatenate records.
Select column_name1,group_concat(concat(`Column_name2`,'separatorValue',`Column_name3`) separator 'separatorValue') as AliasName yourTableName group by column_name1;
The following is an example.
mysql> SELECT -> id,group_concat(concat(`FirstName`,':',`score`) separator ',') -> as FirstNameAndScore from GroupConcatenateDemo group by id;
Here is the output that shows we have successfully concatenated records.
+------+-------------------+ | id | FirstNameAndScore | +------+-------------------+ | 1 | John:94 | | 2 | Bob:98 | | 3 | Carol:100 | +------+-------------------+ 3 rows in set (0.00 sec)