Regex与Like的关系
mysql中我们经常会用到正则表达式就是Like filed like ‘%?%‘ 。但是有时对于一些复杂场景下的正则过滤,单单一个like就显得有些力不从心了
Regex的精华就是 ‘‘ , like ‘%%‘ = regex ‘‘,特殊字符如^、$可以改变%的意思。
- like ‘%304%‘ = regex ‘304‘
- like ‘张%‘ = regex ‘^张‘
- like ‘%03‘ = regex ‘03$‘
- like ‘%3%‘ or like ‘%4%‘ = regex ‘[34]‘ 一个字段包含3或者包含4
- like ‘%3%‘ or like ‘%4%‘ = regex ‘3|4‘ 一个字段包含3或者包含4
# 示例SQL--- # ‘‘ 匹配fw_ver字段中包含‘304‘字符串的所有数据: select * from tbl_upgrade_policy where fw_ver like ‘%304%‘; select * from tbl_upgrade_policy where fw_ver REGEXP ‘304‘; # ^ 匹配输入字符串的开始位置 # 查找operator字段已‘张‘开头的记录 select * from tbl_upgrade_policy where operator like ‘张%‘; select * from tbl_upgrade_policy where operator regexp ‘^李‘; # $ 匹配输入字符串的结束位置 # 查找operator字段已‘03‘结尾的记录 select * from tbl_upgrade_policy where operator like ‘%03‘; select * from tbl_upgrade_policy where operator regexp ‘03$‘; # [...] 字符集合,匹配所包含的任意一个字符。 # 查询出update_type字段下为3或4或5中的任意数字 select * from tbl_upgrade_policy where update_type like ‘%3%‘ or update_type like ‘%4%‘ or update_type like ‘%5%‘; select * from tbl_upgrade_policy where update_type REGEXP ‘[345]‘; # p1|p2|p3 匹配 p1 或 p2 或 p3。 select * from tbl_upgrade_policy where update_type like ‘%3%‘ or update_type like ‘%4%‘; select * from tbl_upgrade_policy where update_type REGEXP ‘3|4‘; select * from tbl_upgrade_policy where update_type like ‘3%‘ or update_type like ‘%5‘; # 注意:‘^[3,5]‘ 匹配以 3或,或5开头的记录 select * from tbl_upgrade_policy where update_type REGEXP ‘^[3,5]|4$‘; # ‘^3,5‘ 匹配以 3,5 开头的记录 select * from tbl_upgrade_policy where update_type REGEXP ‘^3,5|2$‘;