Search for text between delimiters in MySQL

前端 未结 11 2403
情歌与酒
情歌与酒 2021-02-08 03:39

I am trying to extract a certain part of a column that is between delimiters.

e.g. find foo in the following

test \'esf :foo: bar

So in the above I\'d wa

11条回答
  •  闹比i
    闹比i (楼主)
    2021-02-08 04:09

    Here ya go, bud:

    SELECT 
      SUBSTR(column, 
        LOCATE(':',column)+1, 
          (CHAR_LENGTH(column) - LOCATE(':',REVERSE(column)) - LOCATE(':',column))) 
    FROM table
    

    Yea, no clue why you're doing this, but this will do the trick.

    By performing a LOCATE, we can find the first ':'. To find the last ':', there's no reverse LOCATE, so we have to do it manually by performing a LOCATE(':', REVERSE(column)).

    With the index of the first ':', the number of chars from the last ':' to the end of the string, and the CHAR_LENGTH (don't use LENGTH() for this), we can use a little math to discover the length of the string between the two instances of ':'.

    This way we can peform a SUBSTR and dynamically pluck out the characters between the two ':'.

    Again, it's gross, but to each his own.

提交回复
热议问题