Selecting part of a field with a regex

后端 未结 2 1294
刺人心
刺人心 2021-01-19 14:24

I\'ve a table where a 3rd party component stores urls, i would like to get only the id parameter from this url.

With PHP i can do it like this:

2条回答
  •  不要未来只要你来
    2021-01-19 14:45

    No, sad to say MySQL doesn't have a way to apply a regex to a column's contents in a SELECT clause, only a WHERE clause.

    But you can use ordinary (non-regex) string manipulation functions to do this. If the column containing your ampersand-separated parameter string is named url, you can get the id number with this fine string expression, which finds your id number.

      CAST(RIGHT(url, LENGTH(url) - 3 - LOCATE('&id=', url)) AS SIGNED INTEGER)
    

    So, if you want a list of id values from the url columns of table1, you could use this SELECT query.

    SELECT CAST(RIGHT(url, LENGTH(url) - 3 - 
                           LOCATE('&id=', url)) AS SIGNED INTEGER) AS id
      FROM table1
     WHERE url REGEXP '&id=[0-9]+'
    

    As you can see this uses the regexp search function to locate the appropriate rows.

    There is nothing fast about this. Regexp matching can't exploit a MySQL index. If you have the choice of loading your table with the id column pre-extracted you'll be much better off searching when your table gets big.

提交回复
热议问题