gpt4 book ai didi

sql - 为什么这个查询使用多个选择比使用 between 查询更快?

转载 作者:行者123 更新时间:2023-12-04 21:43:49 24 4
gpt4 key购买 nike

我在 Sql Server 2008 Express 中有一个表,其中包含 1800 万条记录。结构看起来像这样(简化):

Id、GroupId、值、创建时间

Id为主键,带聚簇索引
GroupId 是非聚集索引

在这种情况下,每 10 行获得一个新的 groupId,这意味着记录 1-10 的 GroupId 为 1,记录 11-20 的 GroupId 为 2,依此类推。

测试 1:此查询运行 23 秒并返回 99 条记录:

DECLARE @Start INT
SET @Start = 1050
select * from FieldValues where GroupId between @Start and @Start + 10

测试 2:此查询运行时间为 0 秒并返回 99 条记录:

DECLARE @Start INT
SET @Start = 1050
select * from FieldValues where GroupId = @Start union
select * from FieldValues where GroupId = @Start + 1 union
select * from FieldValues where GroupId = @Start + 2 union
select * from FieldValues where GroupId = @Start + 3 union
select * from FieldValues where GroupId = @Start + 4 union
select * from FieldValues where GroupId = @Start + 5 union
select * from FieldValues where GroupId = @Start + 6 union
select * from FieldValues where GroupId = @Start + 7 union
select * from FieldValues where GroupId = @Start + 8 union
select * from FieldValues where GroupId = @Start + 9 union
select * from FieldValues where GroupId = @Start + 10


注意:由于结果可以缓存,我总是在每次测试之间打乱 @Start 变量以获得非缓存时间估计

为什么这些多项选择(看起来有些初学者已经搞定了)比测试 1 中更优雅的选择快得多?

最佳答案

尝试在查询分析器中使用“Show actual execution plan”,你会看到第二个查询可能通过执行索引查找来获得结果,而前者(较慢)无法做到这一点,因为它不'知道记录是顺序的,因为它使用的索引是非聚集的。

关于sql - 为什么这个查询使用多个选择比使用 between 查询更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/862970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com