MySQL query to concatenate all the values in each row based on the common matching ID

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
(
   StudentId int,
   StudentFirstName varchar(100),
   StudentLastName varchar(100)
);
Query OK, 0 rows affected (0.54 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(1000,'Adam','Smith');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(1000,'John','Doe');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(1000,'David','Miller');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+------------------+-----------------+
| StudentId | StudentFirstName | StudentLastName |
+-----------+------------------+-----------------+
|      1000 | Adam             | Smith           |
|      1000 | John             | Doe             |
|      1000 | David            | Miller          |
+-----------+------------------+-----------------+
3 rows in set (0.00 sec)

Following is the query to concatenate all the values in each row based on the common matching ID −

mysql> select StudentId,group_concat(StudentFirstName),group_concat(StudentLastName) from DemoTable group by StudentId;

This will produce the following output −

+-----------+--------------------------------+-------------------------------+
| StudentId | group_concat(StudentFirstName) | group_concat(StudentLastName) |
+-----------+--------------------------------+-------------------------------+
|      1000 | Adam,John,David                | Smith,Doe,Miller              |
+-----------+--------------------------------+-------------------------------+
1 row in set (0.00 sec)
raja
Published on 27-Sep-2019 07:24:01
Advertisements