Optimal search queries

前端 未结 3 416
有刺的猬
有刺的猬 2021-01-15 14:34

Following on from my last question Sql Server query performance, and discovering that my method of allowing optional parameters in a search query is sub optimal, does anyone

3条回答
  •  被撕碎了的回忆
    2021-01-15 15:15

    In your case, the different queries would use the different indexes.

    You should define a set of indexes you want to use and write an individual query for each set, replacing OR on indexed fields with UNION ALL:

    SELECT  *
    FROM    tables
    WHERE   A = @ID
            AND (c.Surname = @Surname or @Surname IS NULL)
            AND (HP.phonenumber = @Homphone or @Homephone IS NULL)
            AND (MOB.phonenumber = @Mobile or @Mobile IS NULL)
    UNION ALL
    SELECT  *
    FROM    tables
    WHERE   @ID IS NULL
            AND c.Surname = @Surname
            AND (HP.phonenumber = @Homphone or @Homephone IS NULL)
            AND (MOB.phonenumber = @Mobile or @Mobile IS NULL)
    UNION ALL
    SELECT  *
    FROM    tables
    WHERE   @ID IS NULL
            AND @Surname IS NULL
            AND (HP.phonenumber = @Homphone or @Homephone IS NULL)
            AND (MOB.phonenumber = @Mobile or @Mobile IS NULL)
    

提交回复
热议问题