SQL split values to multiple rows

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

    Best Practice. Result:

    SELECT
    SUBSTRING_INDEX(SUBSTRING_INDEX('ab,bc,cd',',',help_id+1),',',-1) AS oid
    FROM
    (
    SELECT @xi:=@xi+1 as help_id from 
    (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) xc1,
    (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) xc2,
    (SELECT @xi:=-1) xc0
    ) a
    WHERE 
    help_id < LENGTH('ab,bc,cd')-LENGTH(REPLACE('ab,bc,cd',',',''))+1
    

    First, create a numbers table:

    SELECT @xi:=@xi+1 as help_id from 
    (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) xc1,
    (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) xc2,
    (SELECT @xi:=-1) xc0;
    
    | help_id  |
    | --- |
    | 0   |
    | 1   |
    | 2   |
    | 3   |
    | ...   |
    | 24   |
    

    Second, just split the str:

    SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('ab,bc,cd',',',help_id+1),',',-1) AS oid
    FROM
    numbers_table
    WHERE
    help_id < LENGTH('ab,bc,cd')-LENGTH(REPLACE('ab,bc,cd',',',''))+1
    
    | oid  |
    | --- |
    | ab   |
    | bc   |
    | cd   |
    

提交回复
热议问题