使用索引扫描而不是查找查找
Using Index scan instead of seek with lookup
我有一个 table 结构如下:
CREATE TABLE Article
(
id UNIQUEIDENTIFIER PRIMARY KEY,
title VARCHAR(60),
content VARCHAR(2000),
datePosted DATE,
srcImg VARCHAR(255),
location VARCHAR(255)
);
然后我在位置上放置了一个非聚集索引:
CREATE NONCLUSTERED INDEX Articles_location
ON Articles (location);
运行 像这样的查询:
select a.content
from Articles a
where a.location = 'Japan, Tokyo';
结果:"Index Scan (Clustered)"
运行 另一个这样的查询:
select a.location
from Articles a
where a.location = 'Japan, Tokyo';
结果:"Index Seek (NonClustered)"
所以非聚集索引正在工作。为什么当我按其他列搜索但进行扫描时,它不进行查找查找?
- table中的总行数是200
- 此查询检索到的行总数为 86
看起来查询优化器决定扫描 table 而不是使用基于数据选择性的索引。
直接引用 table 实际上可能比通过索引查找然后执行 KeyLookup 更快。如果 table 有更多行(> 10k),情况可能并非如此。这里 200 中的 86 超过了 40%。
select a.content from Articles a where a.location = 'Japan, Tokyo';
-- clustered index scan
select a.location from Articles a where a.location = 'Japan, Tokyo';
-- covering index
Thus, a seek is generally a more efficient strategy if we have a highly selective seek predicate; that is, if we have a seek predicate that eliminates a large fraction of the table.
我有一个 table 结构如下:
CREATE TABLE Article
(
id UNIQUEIDENTIFIER PRIMARY KEY,
title VARCHAR(60),
content VARCHAR(2000),
datePosted DATE,
srcImg VARCHAR(255),
location VARCHAR(255)
);
然后我在位置上放置了一个非聚集索引:
CREATE NONCLUSTERED INDEX Articles_location
ON Articles (location);
运行 像这样的查询:
select a.content
from Articles a
where a.location = 'Japan, Tokyo';
结果:"Index Scan (Clustered)"
运行 另一个这样的查询:
select a.location
from Articles a
where a.location = 'Japan, Tokyo';
结果:"Index Seek (NonClustered)"
所以非聚集索引正在工作。为什么当我按其他列搜索但进行扫描时,它不进行查找查找?
- table中的总行数是200
- 此查询检索到的行总数为 86
看起来查询优化器决定扫描 table 而不是使用基于数据选择性的索引。
直接引用 table 实际上可能比通过索引查找然后执行 KeyLookup 更快。如果 table 有更多行(> 10k),情况可能并非如此。这里 200 中的 86 超过了 40%。
select a.content from Articles a where a.location = 'Japan, Tokyo';
-- clustered index scan
select a.location from Articles a where a.location = 'Japan, Tokyo';
-- covering index
Thus, a seek is generally a more efficient strategy if we have a highly selective seek predicate; that is, if we have a seek predicate that eliminates a large fraction of the table.