码迷,mamicode.com
首页 > 数据库 > 详细

MySQL之模糊查询

时间:2020-10-27 11:46:12      阅读:32      评论:0      收藏:0      [点我收藏+]

标签:contain   模糊   into   介绍   substr   常用   创建   查询   toc   

前情提要

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之模糊查询

标签:contain   模糊   into   介绍   substr   常用   创建   查询   toc   

原文地址:https://www.cnblogs.com/ringbug/p/13882322.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!