MySQL substring extraction using delimiter

后端 未结 3 593
情歌与酒
情歌与酒 2020-11-30 12:07

I want to extract the substrings from a string in MySQL. The string contains multiple substrings separated by commas(\',\'). I need to extract these substrings using any MyS

相关标签:
3条回答
  • 2020-11-30 12:49

    A possible duplicate of this: Split value from one field to two

    Unfortunately, MySQL does not feature a split string function. As in the link above indicates there are User-defined Split function.

    A more verbose version to fetch the data can be the following:

    SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(colors, ',', 1), ',', -1) as colorfirst,
           SUBSTRING_INDEX(SUBSTRING_INDEX(colors, ',', 2), ',', -1) as colorsecond
    ....
           SUBSTRING_INDEX(SUBSTRING_INDEX(colors, ',', n), ',', -1) as colornth
      FROM product;
    
    0 讨论(0)
  • 2020-11-30 12:53

    Check the use of SPLIT_STR function here at line 64 to 69

    0 讨论(0)
  • 2020-11-30 13:02

    Based on https://blog.fedecarg.com/2009/02/22/mysql-split-string-function/, here is a way to access a value from a delimiter separated array:

    /*
      usage:
        SELECT get_from_delimiter_split_string('1,5,3,7,4', ',',  1); -- returns '5'
        SELECT get_from_delimiter_split_string('1,5,3,7,4', ',',  10); -- returns ''
    */
    CREATE FUNCTION get_from_delimiter_split_string(
      in_array varchar(255),
      in_delimiter char(1),
      in_index int
    )
    RETURNS varchar(255) CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci
    RETURN REPLACE( -- remove the delimiters after doing the following:
      SUBSTRING( -- pick the string
        SUBSTRING_INDEX(in_array, in_delimiter, in_index + 1), -- from the string up to index+1 counts of the delimiter
        LENGTH(
          SUBSTRING_INDEX(in_array, in_delimiter, in_index) -- keeping only everything after index counts of the delimiter
        ) + 1
      ),
      in_delimiter,
      ''
    );
    

    here are the docs for the string operators for reference: https://dev.mysql.com/doc/refman/8.0/en/string-functions.html

    0 讨论(0)
提交回复
热议问题