MySQL query to group concat distinct by Id?


Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable values(100,'Chris');
Query OK, 1 row affected (0.44 sec)
mysql> insert into DemoTable values(200,'Robert');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(100,'Chris');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(300,'David');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(400,'Mike');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(400,'Mike');
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------+--------+
| Id   | Name   |
+------+--------+
|  100 | Chris  |
|  200 | Robert |
|  100 | Chris  |
|  300 | David  |
|  400 | Mike   |
|  400 | Mike   |
+------+--------+
6 rows in set (0.00 sec)

Following is the query to MySQL group Concat distinct by Id −

mysql> select group_concat(Name)
from
(
   select distinct Id,Name from DemoTable
)
tbl;

This will produce the following output −

+-------------------------+
| group_concat(Name)      |
+-------------------------+
| Chris,Robert,David,Mike |
+-------------------------+
1 row in set (0.00 sec)

Updated on: 26-Sep-2019

353 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements