mysql几种模糊查询方法


like

-- 没有用到索引
select * from t_user where user_name like '%test%';
-- 用到索引但是不通用
select * from t_user where user_name like 'test%';

locate

-- LOCATE('substr',str,pos)
-- pos不填:返回substr在str中第一次出现的位置,如果不存在,返回值为0
-- pos存在:返回pos之后第一次出现的位置
select * from t_user where locate('test',user_name)>0;

position

-- 同locate
select * from t_user where position('test' in user_name);

instr

-- 查找一个字符串在另一个字符串中首次出现的位置
select * from t_user where instr(user_name,'test')>0;

find_in_set

FIND_IN_SET(str,strList)

  • str 要查询的字符串
  • strList 字段名,参数以 , 分隔,如 (1,2,6,8)
-- 测试及结果
mysql> select find_in_set('1','1,2,3,4,5,6');
+--------------------------------+
| find_in_set('1','1,2,3,4,5,6') |
+--------------------------------+
|                              1 |
+--------------------------------+
1 row in set

mysql> select find_in_set('2','1,2,3,4,5,6');
+--------------------------------+
| find_in_set('2','1,2,3,4,5,6') |
+--------------------------------+
|                              2 |
+--------------------------------+
1 row in set

mysql> select find_in_set('','1,2,3,4,5,6');
+-------------------------------+
| find_in_set('','1,2,3,4,5,6') |
+-------------------------------+
|                             0 |
+-------------------------------+
1 row in set

mysql> select find_in_set('2','');
+---------------------+
| find_in_set('2','') |
+---------------------+
|                   0 |
+---------------------+
1 row in set

mysql> select find_in_set('7','1,2,3,4,5,6');
+--------------------------------+
| find_in_set('7','1,2,3,4,5,6') |
+--------------------------------+
|                              0 |
+--------------------------------+
1 row in set

mysql> select find_in_set(null,'1,2,3,4,5,6');
+---------------------------------+
| find_in_set(null,'1,2,3,4,5,6') |
+---------------------------------+
| NULL                            |
+---------------------------------+
1 row in set

mysql> select find_in_set('7',null);
+-----------------------+
| find_in_set('7',null) |
+-----------------------+
| NULL                  |
+-----------------------+
1 row in set

文章作者: wuzhiyong
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 wuzhiyong !
评论
 上一篇
docker-compose常用命令 docker-compose常用命令
命令 说明 build 构建或重建服务 help 命令帮助 kill 杀掉容器 logs 显示容器的输出内容 port 打印绑定的开放端口 ps 显示容器 pull 拉取服务镜像 restart 重启
2020-06-22
下一篇 
vmware虚拟机意外关机后启动报错 vmware虚拟机意外关机后启动报错
虚拟机意外关机后启动报错 以独占方式锁定此配置文件失败。可能其它正在运行VMware进程在使用此配置文件 解决办法任务管理器 -> 启动 -> VMware Tray Process -> 禁用重启机器VMware Tr
2020-06-18
  目录