
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Group Concat Distinct by ID in MySQL
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)
Advertisements