Can you split/explode a field in a MySQL query?

后端 未结 17 845
无人及你
无人及你 2020-11-22 04:03

I have to create a report on some student completions. The students each belong to one client. Here are the tables (simplified for this question).

CREATE TAB         


        
17条回答
  •  情歌与酒
    2020-11-22 04:42

    I used the above logic but modified it slightly. My input is of format : "apple:100|pinapple:200|orange:300" stored in a variable @updtAdvanceKeyVal

    Here is the function block :

    set @res = "";
    
    set @i = 1;
    set @updtAdvanceKeyVal = updtAdvanceKeyVal;
    
    REPEAT
    
    
     -- set r =  replace(SUBSTRING(SUBSTRING_INDEX(@updtAdvanceKeyVal, "|", @i),
     --  LENGTH(SUBSTRING_INDEX(@updtAdvanceKeyVal, "|", @i -1)) + 1),"|","");
    
    -- wrapping the function in "replace" function as above causes to cut off a character from
     -- the 2nd splitted value if the value is more than 3 characters. Writing it in 2 lines causes no such problem and the output is as expected
    -- sample output by executing the above function :
    -- orange:100
    -- pi apple:200    !!!!!!!!strange output!!!!!!!!
    -- tomato:500
    
          set @r =  SUBSTRING(SUBSTRING_INDEX(@updtAdvanceKeyVal, "|", @i),
                      LENGTH(SUBSTRING_INDEX(@updtAdvanceKeyVal, "|", @i -1)) + 1);
    
          set @r = replace(@r,"|","");
    
          if @r <> "" then
    
                  set @key = SUBSTRING_INDEX(@r, ":",1);
                  set @val = SUBSTRING_INDEX(@r, ":",-1);
    
                  select @key, @val;
          end if;
    
          set @i = @i + 1;
    
         until @r = ""
    END REPEAT;
    

提交回复
热议问题