我有一个奇怪的情况,我不太明白。
我有一张这样的桌子:
CREATE TABLE dbo.cc_demo
(
id INT IDENTITY PRIMARY KEY,
up_action INT,
down_action INT,
last_action_date DATETIME
);
INSERT dbo.cc_demo ( up_action, down_action, last_action_date )
SELECT TOP 5000000
nums.num % 500000, nums.num % 500000, DATEADD(MINUTE, nums.num, GETDATE())
FROM
( SELECT ROW_NUMBER() OVER ( ORDER BY ( SELECT NULL )) AS num
FROM master..spt_values AS sv
CROSS JOIN master..spt_values AS sv2 ) AS nums;
如果我运行这个查询,计划只是一个常规的聚簇索引扫描。
SELECT *
FROM dbo.cc_demo AS cd
WHERE cd.last_action_date >= '20270601'
AND cd.last_action_date < '20270901';
但是,如果我添加一个计算列并为其编制索引,我的计划就会发生最坏的变化。
ALTER TABLE dbo.cc_demo
ADD total_actions AS up_action + down_action;
CREATE INDEX ix_total_actions ON dbo.cc_demo (total_actions);
现在它扫描聚集索引,然后稍后过滤掉东西!
它要求一个索引,这会将计划改回我所期望的,但为什么我必须添加它?
CREATE NONCLUSTERED INDEX [WORLDSTAR]
ON dbo.cc_demo ( last_action_date )
INCLUDE ( up_action, down_action, total_actions );
这似乎不合逻辑。
表现:
预计算列:
Table 'cc_demo'. Scan count 1, logical reads 17990,
SQL Server Execution Times:
CPU time = 234 ms, elapsed time = 224 ms.
后计算列 + 索引:
Table 'cc_demo'. Scan count 1, logical reads 17990
SQL Server Execution Times:
CPU time = 594 ms, elapsed time = 591 ms.
这是细分:
- 当我添加计算列时,计划没有改变
- 当我索引计算列时,它确实
- 我还不太担心性能
- 我很好奇为什么在我索引计算列后计划会这样改变