首页 > 技术文章 > MySQL使用内置函数来进行模糊搜索locate()与like的不同

kdx-2 2018-04-20 12:47 原文

首先创建一个表class,插入数据。

CREATE TABLE `class` (
  `id` int(10) DEFAULT NULL,
  `name` varchar(32) DEFAULT NULL,
  `age` varchar(32) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into `class` (`id`, `name`, `age`) values('1','张三%%%','55');
insert into `class` (`id`, `name`, `age`) values('2','李四%','25');
insert into `class` (`id`, `name`, `age`) values('3','王五','22');
insert into `class` (`id`, `name`, `age`) values('4','贼溜','28');

如果 在CMD中操作mysql数据库出现中文乱码解决方案

set charset gbk;

使用LOCATE()

mysql> select * from class;
+------+---------+------+
| id   | name    | age  |
+------+---------+------+
|    1 | 张三%%%     | 55   |
|    2 | 李四%       | 25   |
|    3 | 王五        | 22   |
|    4 | 贼溜        | 28   |
+------+---------+------+
4 rows in set (0.00 sec)

mysql> SELECT NAME FROM class WHERE LOCATE('%',NAME)>0;
+---------+
| NAME    |
+---------+
| 张三%%%     |
| 李四%       |
+---------+

使用like模糊查询

mysql> select * from class where name like '%%%';
+------+---------+------+
| id   | name    | age  |
+------+---------+------+
|    1 | 张三%%%     | 55   |
|    2 | 李四%       | 25   |
|    3 | 王五        | 22   |
|    4 | 贼溜        | 28   |
+------+---------+------+

like认为%是查询所有。

 

推荐阅读