T-SQL 中 LIKE 关键字的性能问题
我的表中有多个记录,如下所示:
COLUMN1 | NUMBER
--------------------------------------
'http://namespace1/#1'| 1
'http://namespace1/#2'| 0
'http://namespace1/#3'| 0
'http://namespace1/#4'| 0
'http://namespace2/#1'| 0
'http://namespace2/#2'| 0
'http://namespace2/#3'| 0
'http://namespace2/#4'| 1
...
现在,我的查询如下所示:
SELECT COLUMN1 FROM MyTable WHERE NUMBER = 1 AND COLUMN1 LIKE 'http://namespace1/%'
该查询的问题是,当表中有大量记录时,它的速度非常慢。只能返回一条记录。
有没有比这个查询更快的替代方案?
I have multiple records in a table that look like this:
COLUMN1 | NUMBER
--------------------------------------
'http://namespace1/#1'| 1
'http://namespace1/#2'| 0
'http://namespace1/#3'| 0
'http://namespace1/#4'| 0
'http://namespace2/#1'| 0
'http://namespace2/#2'| 0
'http://namespace2/#3'| 0
'http://namespace2/#4'| 1
...
Right now, my query looks like this:
SELECT COLUMN1 FROM MyTable WHERE NUMBER = 1 AND COLUMN1 LIKE 'http://namespace1/%'
The problem with this query is thats it is very very slow when there is a lot of records in the table. Only one record can be returned.
Is there a faster alternative to this query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要在 NUMBER 和 COLUMN1 列上都有索引才能在此处发挥作用,因为 WHERE 子句有 2 个条件。
当前 COLUMN1 索引要么因 NUMBER = 1 位而被忽略,要么与键查找一起使用以获取 NUMBER。不管怎样,这解释了OP所看到的。
编辑:
索引是
(NUMBER,COLUMN1)
还是(COLUMN1,NUMBER)
是反复试验。如果 NUMBER 上只有 2 个值,我怀疑第二个,但是 YMMV
You need an index on both NUMBER and COLUMN1 columns to be useful here because the WHERE clause has 2 conditions.
The current COLUMN1 index is either ignored because of the NUMBER = 1 bit, or it is used with a key lookup to get NUMBER. Either way, this explains what OP sees.
Edit:
Whether the index is
(NUMBER,COLUMN1)
or(COLUMN1,NUMBER)
is trial and error.I suspect the second one if there are only 2 values on NUMBER, but YMMV
在 column1 和 number 列上添加索引。尝试两种方法,第 1 列和数字/数字和第 1 列。一次尝试一个索引。根据数据的不同,它可能会产生影响。
索引有助于 like 命令,其中 % 不在 like 值的前面。在这种情况下,它应该有很大帮助。
Add an index on the column1 and number columns. Try it both ways, column1 and number/number and column1. Try the indexes one at a time. Depending on the data it could make a difference.
Indexes help with the like command where the % is not at the front of the like value. In this case it should help a lot.
由于只能返回一条记录,因此可以执行top(1)。在某些情况下,top(1) 会在第一次匹配时停止条件循环(当没有
order by
时)。查询速度会快很多。Since only one record can be returned, it is possible to perform a top(1). In some circumstances, a top(1) will stop the condition loop at the first match (when there is no
order by
). The query will be way faster.覆盖索引< /a> 在
COLUMN1
和NUMBER
上,无论是聚集的还是非聚集的,可能是最好的选择。A covering index on
COLUMN1
andNUMBER
, either clustered or nonclustered, might be the best option.