简体   繁体   English

如何改善SQL时间戳范围查询?

[英]How to improve a SQL timestamp range query?

I have a table records having three fields: 我有一个包含三个字段的表records

id - the row id
value - the row value
source - the source of the value
timestamp - the time when the row was inserted (should this be a unix timestamp or a datetime?)

And I want to perform a query like this: 我想执行这样的查询:

SELECT timestamp, value FROM records WHERE timestamp >= a AND timestamp <= b

However in a table with millions of records this query is super inefficient! 但是,在具有数百万条记录的表中,此查询效率极低!

I am using Azure SQL Server as the DBMS. 我正在使用Azure SQL Server作为DBMS。 Can this be optimised? 可以优化吗?

If so can you provide a step-by-step guide to do it (please don't skip "small" steps)? 如果可以,您是否可以提供逐步指南(请不要跳过“小”步骤)? Be it creating indexes, redesigning the query statement, redesigning the table (partitioning?)... 是创建索引,重新设计查询语句,重新设计表(分区?)...

Thanks! 谢谢!

After creating an index on the field you want to search, you can use a between operator so it is a single operation, which is most efficient for sql. 在要搜索的字段上创建索引后,可以使用between运算符,因此它是单个操作,对于sql最有效。

SELECT XXX FROM ABC WHERE DateField BETWEEN '1/1/2015' AND '12/31/2015' 从'1/1/2015'和'12 / 31/2015'之间的ABC WHERE DateField中选择XXX

Also, in SQL Server 2016 you can create range indexes for use on things like time-stamps using memory optimized tables. 此外,在SQL Server 2016中,您可以使用内存优化表创建范围索引,以用于诸如时间戳记之类的事情。 That's really the way to do it. 确实是这样做的方法。

I would recommend using the datetime, or even better the datetime2 data type to store the date data (datetime2 being better as it has a higher level of precision, and with lower precision levels will use less storage). 我建议使用datetime或更好的datetime2数据类型来存储日期数据(datetime2更好,因为它具有较高的精度级别,而精度较低的级别将使用较少的存储空间)。

As for your query, based upon the statement you posted you would want the timestamp to be the key column, and then include the value. 对于您的查询,根据您发布的语句,您希望时间戳记为键列,然后包含该值。 This is because you are using the timestamp as your predicate, and returning the value along with it. 这是因为您将时间戳记用作谓词,并随其返回值。

CREATE NONCLUSTERED INDEX IX_Records_Timestamp on Records (Timestamp) INCLUDE (Value)

This being said, be careful of your column names. 话虽如此,请注意您的列名。 I would highly recommend not using reserved keywords for columns names as they can be a lot more difficult to work with. 我极力建议您不要对列名使用保留关键字,因为使用它们可能会更加困难。

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

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