Tutorialspoint

How to concatenate MySQL distinct query results into a string?


1 Answer
Rama Giri

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;

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;

This will produce the following output −

+--------------------------+
| group_concat(tbl.sub)    |
+--------------------------+
| C,C++,MongoDB,MySQL,Java |
+--------------------------+
1 row in set (0.04 sec)

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.