你知道什么是 MySQL 的模糊查询?
作者 | luanhz
责编 | 郭芮
1SELECT words FROM tests WHERE words LIKE 'hello%';
1SELECT words FROM tests WHERE words LIKE 'hello_%';
1SELECT words FROM tests WHERE words REGEXP 'hello';
1SELECT words FROM tests WHERE words REGEXP '^hello';
1SELECT INSTR("hello,world", 'hello');-- 1
2SELECT LOCATE('hello', "hello,world");-- 1
3SELECT POSITION('hello' in "hello, world"); -- 1
1SELECT words FROM tests WHERE INSTR(words, 'hello');
2SELECT words FROM tests WHERE LOCATE('hello', words);
3SELECT words FROM tests WHERE POSITION('hello' in words);
1SELECT words FROM tests WHERE MATCH(words) against('hello');
1SELECT MATCH(words) against('hello') FROM tests;
1CREATE TABLE IF NOT EXISTS sayings(says TEXT, FULLTEXT (says));
1from pyquery import PyQuery as pq
2from pymysql import connect
3
4doc = pq(url='http://www.1juzi.com/new/43141.html', encoding = 'gb18030')
5items=doc("div.content>p:nth-child(2n+1)").items()
6hots = [item.text() for item in items]
7with connect(host="localhost", user="root", password="123456", db='teststr', charset='utf8') as cur:
8 sql_insert = 'insert into sayings values (%s);'
9 for _ in range(100):
10 cur.executemany(sql_insert, hots)
1-- LIKE通配符
2SELECT says FROM sayings WHERE says LIKE '%success%'
3> OK
4> 时间: 0.036s
5
6-- REGEXP正则匹配
7SELECT says FROM sayings WHERE says REGEXP 'success'
8> OK
9> 时间: 0.053s
10
11-- 内置函数查找
12SELECT says FROM sayings WHERE INSTR(says, 'success')
13> OK
14> 时间: 0.045s
15
16SELECT says FROM sayings WHERE LOCATE('success', says)
17> OK
18> 时间: 0.044s
19
20SELECT says FROM sayings WHERE POSITION('success' in says)
21> OK
22> 时间: 0.047s
23
24-- 全文索引
25SELECT says FROM sayings WHERE MATCH(says) against('Success')
26> OK
27> 时间: 0.006s
1SELECT says FROM sayings WHERE says LIKE 'success%'
2> OK
3> 时间: 0.015s
4
5SELECT says FROM sayings WHERE says REGEXP '^success'
6> OK
7> 时间: 0.046s
8
9SELECT says FROM sayings WHERE INSTR(says, 'success')=1
10> OK
11> 时间: 0.042s
12
13SELECT says FROM sayings WHERE LOCATE('success', says)=1
14> OK
15> 时间: 0.051s
16
17SELECT says FROM sayings WHERE POSITION('success' in says)=1
18> OK
19> 时间: 0.049s
20
21SELECT says FROM sayings WHERE MATCH(says) against('Success')
22> OK
23> 时间: 0.007s
Like通配符用于查询目标字段与模式串完全匹配的记录,且无法应用全文索引提高查询速度,但以特定字符开头的模糊查询比以"%"开头时速度提升明显;
RegExp正则表达式功能强大,可实现任意模式查询,但执行效率一般;
简单的子串有无查询还可应用MySQL内置函数,包括Instr()、Locate()和Position()等,用法相近,但效率一般;
对于包含全文索引的目标字段查询,应用全文索引查询效率最高,但可定制性差,不支持任意匹配查询;
记录数目较少时,几种查询方式效率均可接受,可根据任务需求灵活选用。
声明:本文为作者投稿,版权归其所有。
今日福利
遇见大咖
由 CSDN 全新专为技术人打造的高端对话栏目《大咖来了》来啦!
CSDN 创始人&董事长、极客帮创投创始合伙人蒋涛携手京东集团技术副总裁、IEEE Fellow、京东人工智能研究院常务副院长、深度学习及语音和语言实验室负责人何晓冬,来也科技 CTO 胡一川,共话中国 AI 应用元年来了,开发者及企业的路径及发展方向!
戳链接或点击阅读原文,直达报名:https://t.csdnimg.cn/uZfQ