简体   繁体   English

将索引扫描转换为索引查找

[英]Turn index scan to an index seek

I've added an index to a table to stop a table scan.我已向表添加索引以停止表扫描。 Now it scans the index instead of the table, why doesn't it perform an index seek?现在它扫描的是索引而不是表,为什么它不执行索引查找?

CREATE PROCEDURE [dbo].[GetPeople]
(
    @PlaceIDs [dbo].[Integers] READONLY,
    @RoleGroupIDs [dbo].[Integers] READONLY
)

AS
BEGIN
    SET NOCOUNT ON;
    SELECT
        PTS.PersonToSiteID,
        PTS.SiteID,
        PTS.PersonID,
        P.PersonID,
        P.GivenName,
        P.FamilyName,
        P.Email,
        P.LandlineNumber,
        P.MobileNumber,
        R.RoleTypeID
    FROM 
        [dbo].[PeopleToPlaces] PTS
        INNER JOIN (Select DISTINCT Identifier FROM @PlaceIDs) Pl ON PTS.PlaceID = Pl.Identifier
        INNER JOIN [dbo].[People] P ON P.PeopleID = PTS.PeopleID 
        INNER JOIN [dbo].[Role] R ON R.RoleID = P.RoleID
        INNER JOIN (Select DISTINCT Identifier FROM @RoleGroupIDs) RG ON R.RoleGroupID = RG.Identifier
END

I have a covering index on the People table and have added the Distinct subqueries whilst testing.我在 People 表上有一个覆盖索引,并在测试时添加了 Distinct 子查询。 There is an index covering the join onto the PTS table and the Identifier field sin the UDTs are both ints matching the type they are joining to.有一个索引覆盖了 PTS 表的连接和 UDT 中的 Identifier 字段都是与它们连接的类型匹配的整数。 I've also tried a SELECT IN compared to a JOIN and can't find a way to avoid the index scan与 JOIN 相比,我还尝试了 SELECT IN 并且找不到避免索引扫描的方法

Used this as a resource so far - https://www.red-gate.com/simple-talk/sql/performance/identifying-and-solving-index-scan-problems/到目前为止将此用作资源 - https://www.red-gate.com/simple-talk/sql/performance/identifying-and-solving-index-scan-problems/

Your query doesn't have a WHERE filtering clause;您的查询没有WHERE过滤子句; it asks for all records in the resultset of that big join.它要求该大连接的结果集中的所有记录。

The query planner would choose index seek over index scan if you wanted just one, or a very small number, of rows in your resultset.如果您只需要结果集中的一个或非常少的行,查询计划器将选择索引搜索而不是索引扫描 index scan is a two-step process: first it seeks to the first row it needs (which could be the first row in the index).索引扫描是一个两步过程:首先它寻找它需要的第一行(可能是索引中的第一行)。 It then scans the index sequentially to get the rest of the rows it needs.然后它依次扫描索引以获取所需行的 rest。

Scanning a covering index is an efficient way to get a multi-row resultset: the query can be satisfied from the index, so the query planner doesn't have to bounce back and forth between the index and the table data itself.扫描覆盖索引是获取多行结果集的有效方法:可以从索引中满足查询,因此查询计划器不必在索引和表数据本身之间来回切换。

All is well here.一切都很好。

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

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