如何避免SQL查询中的条件连接?

时间:2017-03-24 14:35:37

标签: sql sql-server

我们可以避免下面的查询中的条件连接,以使其更快吗?

SELECT *    
FROM tbl_suite(nolock) SU
INNER JOIN tbl_plan(nolock) PL ON Su.planid = PL.planid
    AND Su.planid = '355' 
INNER JOIN tbl_suiteentry(nolock) SUE ON 
CASE WHEN (SUE.testcaseid != 0) AND SU.suiteid = SUE.suiteid THEN 1
     WHEN SUE.SuiteID = SUE.ChildSuiteID THEN 1 
     ELSE 0
     END = 1

3 个答案:

答案 0 :(得分:0)

使用OR

select *
from tbl_suite(nolock) SU
inner join tbl_plan(nolock) PL on Su.planid = PL.planid
    and Su.planid = '355'
inner join tbl_suiteentry(nolock) SUE on (
        SUE.testcaseid != 0
        and SU.suiteid = SUE.suiteid
        )
    or (
        SUE.testcaseid = 0
        and SUE.SuiteID = SUE.ChildSuiteID
        )

在您的情况下,您可以执行以下操作:

select *
from tbl_suite(nolock) SU
inner join tbl_plan(nolock) PL on Su.planid = PL.planid
    and Su.planid = '355'
inner join tbl_suiteentry(nolock) SUE 
on SUE.SuiteID = case when SUE.testcaseid != 0 then SUE.suiteid else SUE.ChildSuiteID end;

答案 1 :(得分:0)

是的,使它们像下面那样复合条件。使用nolock提示每个地方

也没有意义
SELECT *    
FROM tbl_suite(nolock) SU
INNER JOIN tbl_plan(nolock) PL ON Su.planid = PL.planid
INNER JOIN tbl_suiteentry(nolock) SUE ON 
(SUE.testcaseid != 0 AND SU.suiteid = SUE.suiteid)
OR (SUE.SuiteID = SUE.ChildSuiteID)
WHERE Su.planid = '355'; 

答案 2 :(得分:0)

or条款中的

on会让事情变得非常缓慢。但是,我猜你可以通过修改join中的条件来更快地提高这一点:

SELECT *    
FROM tbl_suite SU INNER JOIN
     tbl_plan PL
     ON Su.planid = PL.planid AND Su.planid = '355' INNER JOIN
     tbl_suiteentr SUE
     ON (SUE.testcaseid <> 0 AND SU.suiteid = SUE.suiteid) OR
        (SUE.testcaseid <> 0 AND SU.suiteid = SUE.ChildSuiteID)
---------------------------------^ This is a guess

我发现很难相信你真的希望条件在同一个表中的两列上。