一个查询是否可以对一张表使用多个非聚集索引?
我有一个看起来像这样的查询,
SELECT TOP 1000 C.iId_company
FROM dbo.Company AS C WITH(NOLOCK)
WHERE
C.col_1 LIKE 'something%'
OR C.col_1 LIKE 'something2%'
OR C.col_1 LIKE 'something3%'
OR C.col_2 LIKE 'something%'
OR C.col_2 LIKE 'something2%'
OR C.col_2 LIKE 'something3%'
我试图使该查询更快,并且尝试在 col_1 和 col_2 上添加索引。如果我注释掉有关 col_2 的条件,则查询速度会非常快,对于 col_1 也是如此(如果我注释掉有关 col_1 的条件)。但当我就这样离开时,又是同样的老故事,非常缓慢。
通过查看执行计划,我怀疑一次只使用一个索引,并且 SQL 在使用第一个索引后执行子集扫描。我尝试了不同的方法(为两列创建索引,但也不起作用)
实际上我唯一的解决方案是拆分查询并使用 UNION。有没有一种方法可以使这种查询更快并将其保留在一个查询中?
I have a query that looks like this
SELECT TOP 1000 C.iId_company
FROM dbo.Company AS C WITH(NOLOCK)
WHERE
C.col_1 LIKE 'something%'
OR C.col_1 LIKE 'something2%'
OR C.col_1 LIKE 'something3%'
OR C.col_2 LIKE 'something%'
OR C.col_2 LIKE 'something2%'
OR C.col_2 LIKE 'something3%'
I tried to make that query faster, and I tried adding indexes on col_1 and col_2. If I comment out the conditions concerning col_2, the query is extra-fast, same thing for col_1 (if I comment out conditions about col_1). But when I leave it like that, it's same old story, very slow.
What I suspect from looking at the execution plan, it's that only one index is used at a time and SQL performs a scan of the subset after the first index is used. I tried different things (making an index of both columns, but does not work also)
Actually my only solution would be to split the query and use a UNION. Is there a way to make that kind of query faster and keep it in one query ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用工会。也就是说:
根据需要进行调整(例如,您可能需要将整个内容包装在 select 中,以便您可以添加 order by 子句来获取您认为是前 1000 名的任何内容)。但我认为您会对这个解决方案感到满意。
Use a union. That is:
Adjust as necessary (e.g. you may need to wrap that whole thing in a select so that you can add an order by clause to get whatever you consider to be the top 1000). But I think you'll be happy with this solution.
您的要求指出需要两个单独的索引,您正在搜索的每一列都有一个索引。使用您喜欢的任何 DBA 工具来生成和查看查询的解释计划。现在您可以开始重新处理查询,看看解释计划是否比您之前的尝试更好。您可能需要使用 UNION 或公用表表达式将两个查询组合成一个结果集。
Your requirements point out a need for two separate indexes, one on each column you're searching. Use whatever DBA tool you prefer to generate and view the explain plan for the query. Now you can start re-working the query to see if the explain plan looks any better than your previous attempts. You may need to use a UNION or a common table expression to combine the two queries together into a single result set.