SQL split values to multiple rows

前端 未结 9 1434
刺人心
刺人心 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:42

    If the name column were a JSON array (like '["a","b","c"]'), then you could extract/unpack it with JSON_TABLE() (available since MySQL 8.0.4):

    select t.id, j.name
    from mytable t
    join json_table(
      t.name,
      '$[*]' columns (name varchar(50) path '$')
    ) j;
    

    Result:

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

    View on DB Fiddle

    If you store the values in a simple CSV format, then you would first need to convert it to JSON:

    select t.id, j.name
    from mytable t
    join json_table(
      replace(json_array(t.name), ',', '","'),
      '$[*]' columns (name varchar(50) path '$')
    ) j
    

    Result:

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

    View on DB Fiddle

提交回复
热议问题