SQL split values to multiple rows

前端 未结 9 1421
刺人心
刺人心 2020-11-21 05:28

I have table :

id | name    
1  | a,b,c    
2  | b

i want output like this :

id | name    
1  | a    
1  | b    
1  | c             


        
9条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-21 05:59

    The original question was for MySQL and SQL in general. The example below is for the new versions of MySQL. Unfortunately, a generic query that would work on any SQL server is not possible. Some servers do no support CTE, others do not have substring_index, yet others have built-in functions for splitting a string into multiple rows.

    --- the answer follows ---

    Recursive queries are convenient when the server does not provide built-in functionality. They can also be the bottleneck.

    The following query was written and tested on MySQL version 8.0.16. It will not work on version 5.7-. The old versions do not support Common Table Expression (CTE) and thus recursive queries.

    with recursive
      input as (
            select 1 as id, 'a,b,c' as names
          union
            select 2, 'b'
        ),
      recurs as (
            select id, 1 as pos, names as remain, substring_index( names, ',', 1 ) as name
              from input
          union all
            select id, pos + 1, substring( remain, char_length( name ) + 2 ),
                substring_index( substring( remain, char_length( name ) + 2 ), ',', 1 )
              from recurs
              where char_length( remain ) > char_length( name )
        )
    select id, name
      from recurs
      order by id, pos;
    

提交回复
热议问题