MySQL学习笔记:like和regexp的区别

一、like关键字

  like有两个模式:_和%

  • _:表示单个字符,用来查询定长的数据
select name from table where name like '陈__';
  • %:表示0个或多个任意字符
select name from table where name like '陈%';
select name from table where name like '%宏%';

 

二、regexp关键字

  1.基本字符匹配

select * from table where col regexp '.000';

  2.like匹配整个值 通配符%

  3.regexp可使用正则自由定制 定位符号^$
  4.如果要区分大小写,应该使用BINARY关键字,如where xxx REGEXP BINARY 'Hello.000'
  5.使用|实现or效果

select * from table where col regexp '1000|2000';

  6.匹配几个字符之一,用[和]扩起来

select * from table where col regexp '[abcde]';

  7.匹配范围:[0-9] [A-Z] [a-z]

  • [^0-9] ^表示非,即匹配不是0-9
  • 后面的比前面大
select * from table where col regexp '[0-9]Ton';

  8.匹配特殊字符使用\\进行转义

  • \\.能够匹配.
  • \\f换页
  • \\n换行
  • \\r回车
  • \\t制表
  • \\纵向制表

注意:
  a)为了匹配\本身,需要使用\\\
  b)在一般情况下正则表达式的转义加一个“\”就可以了,在MySQL中需要加两个。


  9.匹配字符类(Posix字符类)

  

  使用的时候需要外面加一层[],例如[[:digit:]]

select * from table where col regexp 'name[[:digit:]]';

  10.匹配多个实例

  • * 0或多个
  • + 1或多个
  • ? 0或1个
  • {n} 指定n个
  • {n,} 不少于n个
  • {n,m} n-m个
select * from table where col regexp '[0-9]{1,3}';

  11.定位符

  • ^ 开始
  • $ 结尾
  • [[:<:]] 词的开始
  • [[:>:]] 词的结尾

  12.^有两个用法,一个是非,一个是文本的开始,用[]中表示非,否则是文本的开始。
  13.MySQL的正则比较简化,没有惰性匹配/贪婪匹配,[]内不支持\w\s\d这种语法,也不支持中文。
  14.这两种模式不要混着用,like模式是不支持正则表达式的,REGEXP模式也不认识_和%。
  15.注意:regexp == rlike 同义词  not like  not regexp
  16.in不支持模糊查询,如:

select * from table where name in ('%宏%');

  17.like concat('%',name,'%')作用在于name为变量,在传参的时候方便。


END 2018-06-01 15:00:02

猜你喜欢

转载自www.cnblogs.com/hider/p/9121704.html
今日推荐