我想在 MySQL 中将选定的值转换为逗号分隔的字符串。
我的初始代码如下:
SELECT id FROM table_level WHERE parent_id = 4;
结果是:
'5' '6' '9' '10' '12' '14' '15' '17' '18' '779'
我想要的输出应该是这样的:
"5,6,9,10,12,14,15,17,18,779"
Use group_concat method in mysql
group_concat
Check this:
SELECT GROUP_CONCAT(id) FROM table_level WHERE parent_id = 4 GROUP BY parent_id;
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;
Try this
SELECT CONCAT('"',GROUP_CONCAT(id),'"') FROM table_level where parent_id=4 group by parent_id;
Result will be
Use group_concat() function of mysql.
It'll give you concatenated string like :
5,6,9,10,12,14,15,17,18,779
The default separator between values in a group is comma(,). To specify any other separator, use SEPARATOR as shown below.
SEPARATOR
SELECT GROUP_CONCAT(id SEPARATOR '|') FROM `table_level` WHERE `parent_id`=4 GROUP BY `parent_id`;
5|6|9|10|12|14|15|17|18|779
To eliminate the separator, then use SEPARATOR ''
SEPARATOR ''
SELECT GROUP_CONCAT(id SEPARATOR '') FROM `table_level` WHERE `parent_id`=4 GROUP BY `parent_id`;
Refer for more info GROUP_CONCAT
First to set group_concat_max_len, otherwise it will not give you all the result:
set group_concat_max_len
SET GLOBAL group_concat_max_len = 999999; SELECT GROUP_CONCAT(id) FROM table_level where parent_id=4 group by parent_id;
Just so for people doing it in SQL server: use STRING_AGG to get similar results.
STRING_AGG
Using the GROUP_CONCAT, here is another way to make it flexible :
SELECT GROUP_CONCAT('"',id,'"') FROM table_level where parent_id=4 GROUP BY parent_id;
This will return the values as :
"181","187","193","199","205","211","217","223","229","235","239","243","247","251"
You can concat using any other separator. This will help in case you want to use the return value directly somewhere.
SELECT GROUP_CONCAT(id) as ids FROM table_level where parent_id=4 group by parent_id;