计数非常慢,有 700 万行
我在表中获得了超过 700 万行,并
SELECT COUNT(*) FROM MyTable where MyColumn like '%some string%'
为我提供了 20,000 行,并且花费了超过 13 秒的时间。
该表在 MyColumn 上有非聚集索引。
有什么办法可以提高速度吗?
I got more than 7 million rows in a table and
SELECT COUNT(*) FROM MyTable where MyColumn like '%some string%'
gives me 20,000 rows and takes more than 13 seconds.
The table has NONCLUSTERED INDEX on MyColumn.
Is there any way to improve speed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
前导通配符搜索
无法
使用 T-SQL 进行优化,并且不会使用索引查看 SQL Server 的 全文搜索
Leading wildcards searches
can not
be optimised with T-SQL and won't use an indexLook at SQL Server's full text search
您可以尝试全文搜索,或者诸如如 Lucene。
You could try a full-text search, or a text search engine such as Lucene.
首先尝试使用二进制排序规则,这意味着复杂的 Unicode 规则将被简单的字节比较所取代。
另外,请参阅 SQL Server MVP Deep Dives 中标题为“构建您自己的索引”的章节 由 Erland Sommarskog 编写
基本思想是向用户引入限制并要求字符串长度至少为三个连续字符。接下来,从 MyColumn 字段中提取所有三个字母序列,并将这些片段与其所属的 MyTable.id 一起存储在表中。查找字符串时,您也将其分成三个字母片段,并查找它们属于哪个记录 ID。这样您可以更快地找到匹配的字符串。简而言之,这就是策略。
本书描述了实现细节以及进一步优化的方法。
Try using a binary collation first, which will mean that the complex Unicode rules are replaced by a simple byte comparison.
Also, have a look at chapter titled 'Build your own index' in SQL Server MVP Deep Dives written by Erland Sommarskog
The basic idea is that you introduce a restriction to the user and require the string to be at least three contiguous characters long. Next, you extract all three letter sequences from the MyColumn field and store these fragments in a table together with the MyTable.id they belong to. When looking for a string, you split it into three letter fragments as well, and look up which record id they belong to. This way you find the matching strings a lot quicker. This is the strategy in a nutshell.
The book describes implementation details and ways to optimise this further.