Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comma separated string of selected values in mysql

I want to convert selected values into a comma separated string in MySQL. My initial code is as follows:

SELECT id FROM table_level where parent_id=4; 

Which produced:

'5' '6' '9' '10' '12' '14' '15' '17' '18' '779' 

My desired output would look like this:

"5,6,9,10,12,14,15,17,18,779" 
like image 965
Karunakar Avatar asked Oct 24 '13 06:10

Karunakar


People also ask

How do I get comma separated values in SQL?

To check if value exists in a comma separated list, you can use FIND_IN_SET() function. Now you can insert some records in the table using insert command. Display all records from the table using select statement.

Can we store comma separated values in MySQL?

A better answer: Don't store a list of comma separated values. Store one value per row, and use a SELECT query with GROUP_CONCAT to generate the comma separated value when you access the database. Is group_concat a mysql only extension?


2 Answers

Check this

SELECT GROUP_CONCAT(id)  FROM table_level where parent_id=4 group by parent_id; 
like image 110
naveen goyal Avatar answered Sep 19 '22 17:09

naveen goyal


If you have multiple rows for parent_id.

SELECT GROUP_CONCAT(id) FROM table_level where parent_id=4 GROUP BY parent_id; 

If you want to replace space with comma.

SELECT REPLACE(id,' ',',') FROM table_level where parent_id=4; 
like image 22
Sanal K Avatar answered Sep 22 '22 17:09

Sanal K