SQL 中基于 where 条件的不同时间的相同执行时间?我该如何解决?

Same execution time for different time based where condition in SQL? How do I solve it?

我的数据库有 700 万条记录和 30 多个变量,下面的查询是根据每天过滤数据,这需要我大约 12 分钟 return 结果

select customername, productname from xyztable where (datatime between '2019-05-17 00:00:00.000'
and '2019-05-18 00:00:00.000')

同样的数据我也需要按小时过滤,如下所示,

select customername, productname from xyztable where (datatime between '2019-05-17 00:00:00.000'
and '2019-05-17 01:00:00.000')

我原以为查询结果会以小时为单位更快,因为数据会非常少。但是和每天的时间一样。

所以基本上每小时和每天的查询都需要 12 分钟 return 结果。

有没有办法让每小时的结果 return 比每天的结果快得多?

这是因为您在字段 "datatime" 上没有索引,所以 SQL 服务器必须读取整个 "xyztable" 才能找到记录。 尝试创建此索引:

CREATE INDEX IX_datatime_xyztable ON xyztable(datatime)

没有执行计划我只能假设有table扫描读取数据。您可以通过创建覆盖索引将其更改为索引查找:

create index ix_MyIndexName
on xyztable (datatime)
include (customername, productname)

您的查询将查找数据时间的第一个值,然后扫描到最后一个符合条件的行。由于 customername 和 productname 包含在索引中,因此不需要在计划中进行查找。