Sree Hari Sree Hari - 1 month ago 12
MySQL Question

How to concat all values of single column in mysql

I have column A in the Sample Table1.
Column A has values as follows.

+----+
| A |
+----+
| a1 |
| a2 |
| a3 |
| a4 |
| a5 |
+----+


I need a query that should give the following output.
All the Values should be

"a1","a2","a3","a4","a5"


Is there a way?

Answer

You could use a combination of CONCAT and GROUP_CONCAT

Query

SELECT GROUP_CONCAT(CONCAT('"', A, '"')) AS `combined_A`
FROM `your_table_name`;

And if you want to remove the duplicates. Then use DISTINCT with GROUP_CONCAT.

Query

SELECT GROUP_CONCAT(DISTINCT CONCAT('"', `A`, '"')) AS `combined_A`
FROM `your_table_name`;

SQL Fiddle demo

Comments