

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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)
- Related Questions & Answers
- How to concatenate results in MongoDB?
- Push query results into variable with MongoDB?
- MySQL query to convert a string into a month (Number)?
- How to concatenate strings from different columns and an additional string using a MySQL query?
- Populating a table from query results in MySQL?
- How to cache query results in Oracle?
- How to merge MySQL results?
- MySQL query to select distinct order by id
- MySQL query to group concat distinct by Id?
- Python program to split string into k distinct partitions
- How to order results of a query randomly & select random rows in MySQL?
- Concatenate string with numbers in MySQL?
- Using DISTINCT and COUNT together in a MySQL Query?
- Counting different distinct items in a single MySQL query?
- How to insert into two tables using a single MySQL query?
Advertisements