Search for text between delimiters in MySQL

前端 未结 11 2410
情歌与酒
情歌与酒 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条回答
  • 2021-02-08 03:50
    mid(col, 
        locate('?m=',col) + char_length('?m='), 
        locate('&o=',col) - locate('?m=',col) - char_length('?m=') 
    )
    

    A bit compact form by replacing char_length(.) with the number 3

    mid(col, locate('?m=',col) + 3, locate('&o=',col) - locate('?m=',col) - 3)
    

    the patterns I have used are '?m=' and '&o'.

    0 讨论(0)
  • 2021-02-08 03:52

    This one looks elegant to me. Strip all after n-th separator, rotate string, strip everything after 1. separator, rotate back.

    select
      reverse(
        substring_index(
          reverse(substring_index(str,separator,substrindex)),
          separator,
          1)
      );
    

    For example:

    select
      reverse(
        substring_index(
          reverse(substring_index('www.mysql.com','.',2)),
          '.',
          1
        )
      );
    
    0 讨论(0)
  • 2021-02-08 03:55

    This should work if the two delimiters only appear twice in your column. I am doing something similar...

    substring_index(substring_index(column,':',-2),':',1)
    
    0 讨论(0)
  • 2021-02-08 03:55

    you can use the substring / locate function in 1 command

    here is a mice tutorial:

    http://infofreund.de/mysql-select-substring-2-different-delimiters/

    The command as describes their should look for u:

    **SELECT substr(text,Locate(' :', text )+2,Locate(': ', text )-(Locate(' :', text )+2)) FROM testtable**

    where text is the textfield which contains "test 'esf :foo: bar"

    So foo can be fooooo or fo - the length doesnt matter :).

    0 讨论(0)
  • 2021-02-08 04:02

    I don't know if you have this kind of authority, but if you have to do queries like this it might be time to renormalize your tables, and have these values in a lookup table.

    0 讨论(0)
  • 2021-02-08 04:02
    select mid(col from locate(':',col) + 1 for 
    locate(':',col,locate(':',col)+1)-locate(':',col) - 1 ) 
    from table where col rlike ':.*:';
    
    0 讨论(0)
提交回复
热议问题