like
和not like
重点:利用_
匹配单个字符,%
匹配任意数目字符(包括0个)。
为了方便讲解,这里先列出user
表的内容
1. 以x开头的name
select * from user where name like "x%";
2. 以G结尾的name
select * from user where name like "%G";
从结果中可以看出,like
不区分大小写。
3. 包含t的name
select * from user where name like "%u%";
正则表达式匹配
规则在「另一篇文章中」有粗略提到,这里做个补充
同样是在where
中使用,关键字为regexp
。
.
匹配单个字符,
[a-z]
匹配从a
到z
之间的小写字母,
[0-9]
匹配从0
到9
之间的数字,相当于\d
,
正则表达式区分大小写,即[a]
只能匹配a
,不能匹配A
,但mysql中似乎不区分大小写
如果希望规则匹配的是开头文本,就使用^
,如果希望在结尾,就使用$
,两者可以一起使用。
1. 匹配包含一个t
的name
select * from user where name regexp "t";
2. 匹配以x
开头的name
select * from user where name regexp "^x";
3. 匹配以o
结尾的name
select * from user where name regexp "o$";
4. 匹配有两个字符的uid
select * from user where uid regexp "^..$" limit 0, 5;
这里是用通配符完成的,也可以用{n}
完成
select * from user where uid regexp "^.{2}$" limit 0, 5;
最后,吐槽下csdn本身
写个MySQL语句教程也能莫名奇妙的「待审核」
不过,说不定是因为检测系统自身乱加了什么敏感词呢