MySQL – How to Generate a String from the Returns of a SELECT Query

MySQL

I need to create a string from data that is extracted from an SQL query, and wish to accomplish it within the SQL Query.

The return is something like

+---------------+
| foo_ids       |
+---------------+
| 63901-63601   |
| 64101-63501   |
| 65101-63501   |
| 65001-63401   |
| 64902-63401   |
| 64901         |
| 62401         |
| 63901         |
+---------------+

I would like to do 2 things to it,

  1. separate strings where there are "-"s
  2. create a string of the ids separated by ","

the strings will only contain numbers and "-"

my final output desired is,

63901,63601,64101,65101,63501,65001,63401,64902,64901,62401

is this possible/realistic or should I have a script or something to fetch it and do some string manipulation in there?

Best Answer

Please try this query:

select group_concat(foo_id separator ',') as ids from
(
select 
 case 
 when locate('-', foo_ids) > 0 then 
  substr(foo_ids, 1, locate('-', foo_ids) - 1) 
 else foo_ids 
 end as foo_id
from foo_table
union all
select 
 case 
 when locate('-', foo_ids) > 0 then 
  substr(foo_ids, (locate(foo_ids, '-') + 1), locate('-', foo_ids) - 1) 
 else null 
 end as foo_id
from foo_table
) t 
where foo_id is not null

http://sqlfiddle.com/#!2/ce1b0a/7