MySQL之模糊查询

Posted ringbug

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL之模糊查询相关的知识,希望对你有一定的参考价值。

前情提要

mysql中的模糊检索方法,总结了有以下几种,下面我们来简单介绍一下

-- 创建表
mysql> create table wuxia
    -> (id int(10) primary key,
    -> name char(10)
    -> );
Query OK, 0 rows affected, 1 warning (0.04 sec)
-- 插入数据
mysql> insert into wuxia (name) value(‘郭靖‘);
Query OK, 1 row affected (0.00 sec)

mysql> insert into wuxia (name) value(‘黄蓉‘);
Query OK, 1 row affected (0.00 sec)

mysql> insert into wuxia (name) value(‘杨过‘);
Query OK, 1 row affected (0.00 sec)

mysql> insert into wuxia (name) value(‘小龙女‘);
Query OK, 1 row affected (0.00 sec)

mysql> insert into wuxia (name) value(‘小高‘);
Query OK, 1 row affected (0.00 sec)

mysql> insert into wuxia (name) value(‘卓东来‘);
Query OK, 1 row affected (0.00 sec)

mysql> insert into wuxia (name) value(‘陆小凤‘);
Query OK, 1 row affected (0.00 sec)

mysql> insert into wuxia (name) value(‘西门吹雪‘);
Query OK, 1 row affected (0.00 sec)
-- 查询表
mysql> select * from wuxia
    -> ;
+----+--------------+
| id | name         |
+----+--------------+
|  1 | 郭靖         |
|  2 | 黄蓉         |
|  3 | 杨过         |
|  4 | 小龙女       |
|  5 | 小高         |
|  6 | 卓东来       |
|  7 | 陆小凤       |
|  8 | 西门吹雪     |
+----+--------------+
8 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

name like ‘%条件%‘,这个是我们最常见常用的

  • 演示结果
mysql> select * from wuxia where name like concat(‘陆‘, ‘%‘);
+----+-----------+
| id | name      |
+----+-----------+
|  7 | 陆小凤    |
+----+-----------+
1 row in set (0.00 sec)

以上是关于MySQL之模糊查询的主要内容,如果未能解决你的问题,请参考以下文章

mysql全文索引之模糊查询

MySQL模糊查询特殊字符如何查询

mysql模糊查询like优化

mysql模糊查询like优化

mysql模糊查询like优化

SSM-MyBatis-05:Mybatis中别名,sql片段和模糊查询加getMapper