前情提要
mysql中的模糊檢索方法,總結了有以下幾種,下面我們來簡單介紹一下
-- 創建表
mysql> create table if not exists wuxia(
-> id int unsigned auto_increment,
-> name varchar(10) not null,
-> primary key (id)
-> );
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| wuxia |
+----------------+
1 row in set (0.00 sec)
-- 插入數據
mysql> insert into wuxia (name) values ('小龍女'),('小高'),('卓東來'),('陸小鳳');
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
-- 查詢表
mysql> select * from wuxia;
+----+-----------+
| id | name |
+----+-----------+
| 13 | 小龍女 |
| 14 | 小高 |
| 15 | 卓東來 |
| 16 | 陸小鳳 |
+----+-----------+
4 rows in set (0.00 sec)
1.LOCATE(substr,str) :
substr 檢索條件;str column(字段);
- 演示結果
mysql> select * from wuxia where locate('龍', name);
+----+-----------+
| id | name |
+----+-----------+
| 4 | 小龍女 |
+----+-----------+
2.INSTR(str,substr)
str column(字段);substr 檢索條件;
- 演示結果
mysql> select * from wuxia where instr(name, '龍');
+----+-----------+
| id | name |
+----+-----------+
| 4 | 小龍女 |
+----+-----------+
1 row in set (0.00 sec)
3.POSITION(substr IN str)
substr 檢索條件;str column(字段);
- 演示結果
mysql> select * from wuxia where position('龍' in name);
+----+-----------+
| id | name |
+----+-----------+
| 4 | 小龍女 |
+----+-----------+
1 row in set (0.00 sec)
4.REGEXP 正則
使用格式為“str REGEXP str_part”,當str字符串中含有str_pat相匹配的字符串時,則返回值1,否則返回0; column regexp '條件'
- 演示結果
mysql> select * from wuxia where name regexp '小';
+----+-----------+
| id | name |
+----+-----------+
| 4 | 小龍女 |
| 5 | 小高 |
| 7 | 陸小鳳 |
+----+-----------+
3 rows in set (0.01 sec)
5.LIKE
column like '%條件%',這種類似方式是我們最常見常用的
- 演示結果
mysql> select * from wuxia where name like concat('陸', '%');
+----+-----------+
| id | name |
+----+-----------+
| 7 | 陸小鳳 |
+----+-----------+
1 row in set (0.00 sec)