- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to concatenate MySQL distinct query results into a string?
Use group_concat() function from MySQL to concatenate. Let us first create a table −
mysql> create table DemoTable -> ( -> Subject varchar(10) -> ); Query OK, 0 rows affected (0.43 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('C'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values('C++'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable values('C++'); Query OK, 1 row affected (0.06 sec) mysql> insert into DemoTable values('MongoDB'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('MySQL'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('MongoDB'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('MongoDB'); Query OK, 1 row affected (0.34 sec) mysql> insert into DemoTable values('Java'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values('Java'); Query OK, 1 row affected (0.10 sec) Display all records from the table using select statement:
mysql> select *from DemoTable;
Output
This will produce the following output −
+---------+ | Subject | +---------+ | C | | C++ | | C++ | | MongoDB | | MySQL | | MongoDB | | MongoDB | | Java | | Java | +---------+ 9 rows in set (0.00 sec)
Following is the query to concatenate SQL distinct query results into a string −
mysql> select group_concat(tbl.sub) from (select Subject sub from DemoTable group by Subject ) tbl;
Output
This will produce the following output −
+--------------------------+ | group_concat(tbl.sub) | +--------------------------+ | C,C++,MongoDB,MySQL,Java | +--------------------------+ 1 row in set (0.04 sec)
Advertisements
To Continue Learning Please Login
Login with Google