mysql> select * from regexp_test where name like 'xiao%';
+------+----------+
| id | name |
+------+----------+
| 1 | xiaoming |
| 2 | xiaohong |
| 3 | xiaohua |
+------+----------+
3 rows in set (0.01 sec)
mysql> explain select * from regexp_test where name like 'xiao%';
mysql> select * from regexp_test where name regexp 'xiao';
+------+----------+
| id | name |
+------+----------+
| 1 | xiaoming |
| 2 | xiaohong |
| 3 | xiaohua |
+------+----------+
3 rows in set (0.00 sec)
2.OR匹配
使用or匹配多个符合条件的数据
mysql> select * from regexp_test where id = 1 or id = 2;
+------+----------+
| id | name |
+------+----------+
| 1 | xiaoming |
| 2 | xiaohong |
+------+----------+
2 rows in set (0.00 sec)
使用regexp匹配多个符合条件的数据
使用regexp的
|
功能类似于在select中使用or
mysql> select * from regexp_test where id regexp '1|2';
+------+----------+
| id | name |
+------+----------+
| 1 | xiaoming |
| 2 | xiaohong |
+------+----------+
2 rows in set (0.00 sec)
3.模糊匹配
使用or模糊匹配
mysql> select * from regexp_test where id = 1 or id = 2 or id = 8;
+------+----------+
| id | name |
+------+----------+
| 1 | xiaoming |
| 2 | xiaohong |
+------+----------+
2 rows in set (0.00 sec)
使用
|
匹配其中符合条件的
mysql> select * from regexp_test where id regexp '1|2|8';
+------+----------+
| id | name |
+------+----------+
| 1 | xiaoming |
| 2 | xiaohong |
+------+----------+
2 rows in set (0.00 sec)
使用
[]
匹配符合条件
mysql> select * from regexp_test where id regexp '[128]';
+------+----------+
| id | name |
+------+----------+
| 1 | xiaoming |
| 2 | xiaohong |
+------+----------+
2 rows in set (0.00 sec)
4.匹配范围
[123456789]
即为匹配到123456789这个集合
[1-9]
即为匹配到123456789这个集合
[a-z]
匹配任意字母
mysql> select * from regexp_test where name regexp '[a-z]';
+------+----------+
| id | name |
+------+----------+
| 1 | xiaoming |
| 2 | xiaohong |
| 3 | xiaohua |
| 4 | zhangsan |
| 5 | lisi |
| 6 | liwu |
| 7 | liliu9 |
+------+----------+
7 rows in set (0.00 sec)
mysql> select * from regexp_test where id regexp '[0-9]';
+------+----------+
| id | name |
+------+----------+
| 1 | xiaoming |
| 2 | xiaohong |
| 3 | xiaohua |
| 4 | zhangsan |
| 5 | lisi |
| 6 | liwu |
| 7 | liliu9 |
+------+----------+
7 rows in set (0.00 sec)
mysql> select * from regexp_test where name regexp '[a-z][0-9]$';
+------+--------+
| id | name |
+------+--------+
| 7 | liliu9 |
+------+--------+
1 row in set (0.01 sec)
案例二:匹配以数字开头
mysql> select * from regexp_test where name regexp '^[0-9][a-z]';
+------+-------+
| id | name |
+------+-------+
| 9 | 1zbc |
| 10 | 1qwr2 |
+------+-------+
2 rows in set (0.00 sec)
案例三:匹配以数字开头,以数字结尾
mysql> select * from regexp_test where name regexp '^[0-9][a-z]*[0-9]$';
+------+-------+
| id | name |
+------+-------+
| 10 | 1qwr2 |
+------+-------+
1 row in set (0.00 sec)