字符串匹配查询
? ? ? ? ? mysql中數據有兩個運算符來提供字符字符串查詢匹配的,分別是like和regexp,下面來看一下。
mysql> select * from tmp; +------+----------+ | id | name | +------+----------+ | 2 | lisi | | 1 | zhangsan | | 3 | NULL | +------+----------+ 3 rows in set (0.00 sec)對于like,'%'匹配任何數目的字符,甚至包括0字符,'_'只能匹配一個字符。
mysql> select * from tmp where name like 'li'; Empty set (0.00 sec)直接匹配,不適用匹配符這樣會失敗。
mysql> select * from tmp where name like 'l%'; +------+------+ | id | name | +------+------+ | 2 | lisi | +------+------+ 1 row in set (0.00 sec)mysql> select * from tmp where name like 'lis%'; +------+------+ | id | name | +------+------+ | 2 | lisi | +------+------+ 1 row in set (0.00 sec)mysql> select * from tmp where name like 'z%'; +------+----------+ | id | name | +------+----------+ | 1 | zhangsan | +------+----------+ 1 row in set (0.00 sec)mysql>%匹配任意數目的字符。
mysql> select * from tmp where name like 'lis_'; +------+------+ | id | name | +------+------+ | 2 | lisi | +------+------+ 1 row in set (0.00 sec)mysql> select * from tmp where name like 'li_'; Empty set (0.00 sec)mysql>'_'只能匹配一個字符。
對于regexp運算符,先看看不帶任何匹配符的情況。
mysql> select * from tmp where name regexp 'li'; +------+------+ | id | name | +------+------+ | 2 | lisi | +------+------+ 1 row in set (0.00 sec)mysql> select * from tmp where name regexp 'zh'; +------+----------+ | id | name | +------+----------+ | 1 | zhangsan | +------+----------+ 1 row in set (0.00 sec)也是可以進行匹配的,這和like運算符不一樣。regexp有一些通配符來提供匹配的,類似于正則表達式。
'^'匹配以該字符后面的字符開頭的字符串。
mysql> select * from tmp where name regexp '^z'; +------+----------+ | id | name | +------+----------+ | 1 | zhangsan | +------+----------+ 1 row in set (0.00 sec)mysql> select * from tmp where name regexp '^w'; Empty set (0.00 sec)'$'匹配以該字符后面的字符結尾的字符串。
mysql> select * from tmp where name regexp 'i$'; +------+------+ | id | name | +------+------+ | 2 | lisi | +------+------+ 1 row in set (0.00 sec)注意'^'和'$'的位置放置。
'.'用來匹配任何一個字符,因為regexp本身就有匹配的字符的能力,我覺得這個有點像雞肋了。
'[...]'用來匹配里面的任何字符。
mysql> select * from tmp where name regexp '[lz]'; +------+----------+ | id | name | +------+----------+ | 2 | lisi | | 1 | zhangsan | +------+----------+ 2 rows in set (0.00 sec)'*'匹配0個或多個在它前面的字符,0個也行,那不是匹配所有,即所以的記錄都行。
mysql> select * from tmp where name regexp '0*'; +------+----------+ | id | name | +------+----------+ | 2 | lisi | | 1 | zhangsan | +------+----------+ 2 rows in set (0.00 sec)mysql> pipei結果一目了然。
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
總結
- 上一篇: is null和is not null运
- 下一篇: group by+having查询