将CONTAINS与条件逻辑相结合时的效率问题

时间:2015-06-02 08:11:32

标签: sql sql-server tsql

我刚刚对用于返回搜索结果的查询的WHERE子句进行了修改。

我开始时:

WHERE 
(
    CONTAINS(MD_Entity.Forename, @Forename) 
    AND CONTAINS(MD_Entity.Family_Name, @FamilyName)
) 
AND 
(
    MD_Entity_Role.Role_Type = 2
    OR MD_Entity.Do_Not_Transact = 1
)

并将其更改为:

WHERE 
(
    CONTAINS(MD_Entity.Forename, @Forename) 
    AND CONTAINS(MD_Entity.Family_Name, @FamilyName) 
    AND MD_Entity_Role.Role_Type = 2
)
OR 
(
    CONTAINS(MD_Entity.Family_Name, @Forename) 
    AND CONTAINS(MD_Entity.Family_Name, @FamilyName) 
    AND MD_Entity.Do_Not_Transact = 1
)

查询从立即返回结果开始,到了一分钟以后。

我不是SQL专家,所以我显然在这里做了一些效率失误。首先,有人可以解释为什么效率大幅下降,其次,是否有更快的方法来解决我在这里所做的事情?

2 个答案:

答案 0 :(得分:1)

重新排序条件,第一次

越快
WHERE 
(   1 = 1
    AND MD_Entity_Role.Role_Type = 2
    AND CONTAINS(MD_Entity.Forename, @Forename) 
    AND CONTAINS(MD_Entity.Family_Name, @FamilyName) 

)
OR 
(   1 = 1
    AND MD_Entity.Do_Not_Transact = 1
    AND CONTAINS(MD_Entity.Family_Name, @Forename) 
    AND CONTAINS(MD_Entity.Family_Name, @FamilyName) 
)

使用UNION来避免慢OR条件

WHERE 
    1 = 1
    AND MD_Entity_Role.Role_Type = 2
    AND CONTAINS(MD_Entity.Forename, @Forename) 
    AND CONTAINS(MD_Entity.Family_Name, @FamilyName) 

UNION

WHERE
    1 = 1
    AND MD_Entity.Do_Not_Transact = 1
    AND CONTAINS(MD_Entity.Family_Name, @Forename) 
    AND CONTAINS(MD_Entity.Family_Name, @FamilyName) 

答案 1 :(得分:1)

试试这个 它可能允许查询优化器更快地过滤

WHERE 
CONTAINS(MD_Entity.Family_Name, @FamilyName)
AND 
(
  (
    CONTAINS(MD_Entity.Forename, @Forename) 
    AND MD_Entity_Role.Role_Type = 2
  )
  OR 
  (
    CONTAINS(MD_Entity.Family_Name, @Forename)          
    AND MD_Entity.Do_Not_Transact = 1
  )
)