How to merge rows in MySQL?

MySQLMySQLi Database

To merge rows in MySQL, use GROUP_CONCAT().

Let us first create a table−

mysql> create table DemoTable734 (
   Id int,
   Name varchar(100)
);
Query OK, 0 rows affected (0.73 sec)

Insert some records in the table using insert command−

mysql> insert into DemoTable734 values(101,'John');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable734 values(102,'John');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable734 values(103,'Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable734 values(104,'Chris');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable734 values(104,'Chris');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement−

mysql> select *from DemoTable734;

This will produce the following output -

+------+-------+
| Id   | Name  |
+------+-------+
| 101  | John  |
| 102  | John  |
| 103  | Chris |
| 104  | Chris |
| 104  | Chris |
+------+-------+
5 rows in set (0.00 sec)

Following is the query to merge rows−

mysql> select Name,group_concat(Distinct Id SEPARATOR ',') from DemoTable734 group by Name;

This will produce the following output -

+-------+-----------------------------------------+
| Name  | group_concat(Distinct Id SEPARATOR ',') |
+-------+-----------------------------------------+
| Chris | 103,104                                 |
| John  | 101,102                                 |
+-------+-----------------------------------------+
2 rows in set (0.04 sec)
raja
Published on 22-Aug-2019 11:19:01
Advertisements