Concatenate multiple rows and columns in a single row with MySQL

MySQLMySQLi Database

To concatenate multiple rows and columns in single row, you can use GROUP_CONCAT() along with CONCAT(). Let us first create a table −

mysql> create table DemoTable1463
   -> (
   -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> ClientName varchar(20),
   -> ClientAge int
   -> );
Query OK, 0 rows affected (1.37 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1463(ClientName,ClientAge) values('Adam Smith',34);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1463(ClientName,ClientAge) values('John Doe',29);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable1463(ClientName,ClientAge) values('David Miller',NULL);
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable1463(ClientName,ClientAge) values('John Smith',32);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1463;

This will produce the following output −

+----------+--------------+-----------+
| ClientId | ClientName   | ClientAge |
+----------+--------------+-----------+
|        1 | Adam Smith   |        34 |
|        2 | John Doe     |        29 |
|        3 | David Miller |      NULL |
|        4 | John Smith   |        32 |
+----------+--------------+-----------+
4 rows in set (0.00 sec)

Following is the query to concatenate multiple rows and columns in a single row −

mysql> select group_concat(concat(ClientId,':',ClientName,':',IFNULL(ClientAge,''))) from DemoTable1463;

This will produce the following output −

+------------------------------------------------------------------------+
| group_concat(concat(ClientId,':',ClientName,':',IFNULL(ClientAge,''))) |
+------------------------------------------------------------------------+
| 1:Adam Smith:34,2:John Doe:29,3:David Miller:,4:John Smith:32          |
+------------------------------------------------------------------------+
1 row in set (0.04 sec)
raja
Published on 10-Dec-2019 11:31:55
Advertisements