Sree Hari
Sree Hari

Reputation: 107

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?

Upvotes: 10

Views: 16664

Answers (3)

Ullas
Ullas

Reputation: 11556

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

Upvotes: 17

Raj K Pachauri
Raj K Pachauri

Reputation: 293

Use GROUP_CONCAT() function to achive this.

SELECT GROUP_CONCAT(<Type your column name here> SEPARATOR ', ') FROM <Table Name>;

Query for your provided sample example :

SELECT GROUP_CONCAT(A SEPARATOR ', ')  FROM Table1;

Upvotes: 4

Ramachandran.A.G
Ramachandran.A.G

Reputation: 4948

You will have to use a group concat function to accomplish something similar

SELECT , GROUP_CONCAT(A SEPARATOR ', ') FROM Table1 GROUP BY

In the event you don't have an id you will have to use a constant for the grouping. Also note that the result you have has a 1024 byte character limit unless you override it

Upvotes: 0

Related Questions