简体   繁体   English

如何在SQL Server中使大型IN子句更有效?

[英]How can I make large IN clauses more efficient in SQL Server?

My current query runs very slow when accessing a DB with pretty large tables 当访问具有很大表的数据库时,我当前的查询运行非常慢

SELECT * 
FROM table1
WHERE timestamp BETWEEN 635433140000000000 AND 635433150000000000
  AND ID IN ('element1', 'element2', 'element3', ... , 'element 3002');

As you can see the IN clause has several thousand values. 如您所见, IN子句具有数千个值。 This query is executed roughly every second. 该查询大约每秒执行一次。

Is there another way to write it to improve performance? 还有另一种编写方法来提高性能的方法吗?

将IN的元素添加到索引临时(如果元素更改)或永久表(如果元素是静态的)中,并对其进行内部联接。

This is your query: 这是您的查询:

SELECT *
FROM table1
WHERE timestamp BETWEEN 635433140000000000 AND 635433150000000000 AND
      ID IN ('element1', 'element2', 'element3', ... , 'element 3002');

The query is fine. 查询很好。 Add an index on table1(id, timestamp) . table1(id, timestamp)上添加索引。

The best answer depends on how those element ID listings are selected, but it all comes down to one thing: getting them into a table somewhere that you can join against. 最佳答案取决于如何选择那些element ID列表,但这全都取决于一件事:将它们放入表中可以加入的地方。 That will help performance tremendously. 这将极大地提高性能。 But again, the real question here is how best to get those items into a table, and that will depend on information not yet included in the question. 但是,这里真正的问题是如何最好地将这些项目放入表格中,这将取决于问题中尚未包括的信息。

You should check your execution plan, I guess you could have a parameter sniffing problem caused by your between. 您应该检查执行计划,我猜您可能由于两者之间的原因而导致参数嗅探问题。 Check if the actual rows are way off you expected values. 检查实际行是否偏离您的期望值。 And you can rewrite your IN to a EXISTS, which works inside like a INNER JOIN. 然后,您可以将IN重写为EXISTS,它在内部的工作方式类似于INNER JOIN。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM