如何在MySQL查询中使用正则表达式

3

我在数据库中有以下条目:

id       summary
1       numbers of word 200 in the doc 0x123
2       [main] numbers of word 150 in the doc 0x678
3       numbers of word 678 in the doc 0x4536 
4       this file has empty
5       not completed
6       numbers of word 86542 in the doc 0x6356 

我想从数据库“Page”和表名称“details”中检索与摘要值相关的ID。我希望所有四个ID(1、2、3、6)都具有"文档中单词数 <任意数字>"的摘要值,并且也要处理空格...
1个回答

5

如果你可以接受这种权衡,即%也匹配非数字字符,那么使用LIKE SQL操作符在跨平台上实现这个功能就很简单了。

select * from details where lower(summary) LIKE 'numbers of word % in the doc %'

如果你只想匹配数字和空格,我认为你需要使用正则表达式,在MySQL中,它们是直接支持的。可以参考MySQL 5.1手册第12.5.2节:正则表达式。示例代码如下:

select * from details
where lower(summary) REGEXP '^numbers of word [0-9 ]+ in the doc [0-9x ]+$'

如果您不需要或不想使用大小写不敏感,可以省略对LOWER()的调用。我在第二个正则表达式中包含了x,因为您的数字前缀是0x(十六进制?)。
请记住,索引可能无法与LIKEREGEXP一起使用,这意味着查询将产生相对非常大的I/O成本。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接