前言
MySQL的regexp与LIKE语句非常类似,大部分功能都可以相互替补。之前一直没有使用过,最近在阅读《MySQL必知必会》第九章时,看到了这个内容,在此做下笔记记录一下。
在此之前,首先建立对应的数据表,ddl与dml如下:
create table if not exists test_db.products
(
id int auto_increment
primary key,
prod_name varchar(20) not null
);
INSERT INTO test_db.products (id, prod_name) VALUES (1, 'JetPack 1000');
INSERT INTO test_db.products (id, prod_name) VALUES (2, 'JetPack 2000');
INSERT INTO test_db.products (id, prod_name) VALUES (3, '1 ton anvil');
INSERT INTO test_db.products (id, prod_name) VALUES (4, '2 ton anvil');
INSERT INTO test_db.products (id, prod_name) VALUES (5, 'TNT (1 stick)');
INSERT INTO test_db.products (id, prod_name) VALUES (6, '.5 ton anvil');

常用指令
由于regexp与LIKE的高度相似性,所以学习时以常用的LIKE的指令作为对比学习,有助于记忆。
基本字符匹配
- 全文字匹配
select *
from products
where prod_name regexp '1000';

- 模糊匹配
类似于LIKE语句的 '_'(下划线)单字符匹配。模糊匹配单个字符。
select *
from products
where prod_name regexp '.000';

OR 匹配
select *
from products
where prod_name regexp '1000|2000';

匹配几个字符之一
- 正确用法
select *
from products
where prod_name regexp '[123] ton';

- 错误示例
正则表达式可以用[]
包含内容或者|
竖线 表示或
,但如果使用下面的用法,不能获得正确的结果,因为在最后一个'或'时,MySQL会理解成3 ton
。得到不同的结果。
select *
from products
where prod_name regexp '1|2|3 ton';
