开发者

Regex for MySQL query

开发者 https://www.devze.com 2023-03-11 17:12 出处:网络
I am trying to select a field based on it meeting one of 3 criteria... and I\'m not sure how to do this.I think a RegExp is probably the best method buy I\'m unfamiliar with writing them.

I am trying to select a field based on it meeting one of 3 criteria... and I'm not sure how to do this. I think a RegExp is probably the best method buy I'm unfamiliar with writing them.

Say I have the integer 123, I would like to match the following cases:

123 (thats 123 only with no spaces or other numbers after it) 123-10/12/2007 00:00 (thats 123 with a hyphen and a date, or actually it could be anything after the hyphen) 123_1014859 (thats 123 with an underscore, or again anything after the underscore)

Is there a way to do this us开发者_开发百科ing MySQL?


A regex is plausible, but it's not the best performing option. The last comparison put MySQL's regex support as being par with wildcarding the left side of a LIKE statement -- works, but the slowest of every option available.

Based on your example, you could use:

SELECT t.*
  FROM YOUR_TABLE t
 WHERE t.column LIKE '123-%'
    OR t.column LIKE '123_%'

Another alternative, because OR can be a performance issue too, would be to use a UNION:

SELECT a.*
  FROM YOUR_TABLE a
 WHERE a.column LIKE '123-%'
UNION ALL
SELECT b.*
  FROM YOUR_TABLE b
 WHERE b.column LIKE '123_%'

UNION ALL will return all results from both tables; UNION removes duplicates, and is slower than UNION ALL for that fact.


select * from foo where bar regexp '^123-|_'

(not tested)


I would avoid using regex inside a SQL statement. Someone can correct me if I am wrong, but MySQL has to use another engine to run the regex.

SELECT * FROM table 
  WHERE field like "123" 
    OR field LIKE "123-%" 
    OR field like "123_%";
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号