SQL 服务器中的查询优化

Query optimization in SQL Server

SELECT 
    T2.Entity1Id, T1.Entity1Id  
FROM 
    T1  
FULL OUTER JOIN 
    T2 ON T1.c2 = T2.c2 AND T1.c1 = T2.c1 AND T1.c3 = 1
WHERE 
    ((T1.c1 = 123 ) OR (T2.c1 = 123))  
    AND (T1.c3 = 1 OR T1.c3 IS NULL)

以上查询在 SQL Server 2014 中耗时 12 秒,有什么办法可以调整查询吗? C1、C2、C3 列上有索引。

观察:在上面的查询中,当我从 OR 中删除一个条件时(即

SELECT  
    T2.Entity1Id, T1.Entity1Id  
FROM 
    T1  
FULL OUTER JOIN 
    T2 ON T1.c2 = T2.c2 AND T1.c1 = T2.c1  AND T1.c3 = 1
WHERE 
    (T1.c1 = 123) AND (T1.c3 = 1 OR T1.c3 IS NULL)

然后它会在 0 秒内返回结果。

每个 table 有大约 500'000 条记录。

首先,最终条件(T1.c3 = 1 OR T1.c3 IS NULL)是多余的。鉴于 join 条件,这些是唯一可能的值。所以,查询是:

SELECT T2.Entity1Id, T1.Entity1Id  
FROM T1 FULL OUTER JOIN
     T2
     ON T1.c2 = T2.c2 AND T1.c1 = T2.c1  AND T1.c3 = 1
WHERE (T1.c1 = 123 ) OR (T2.c1 = 123)

如果这没有很好的性能,请考虑将其分成两个查询:

SELECT T2.Entity1Id, T1.Entity1Id  
FROM T1 LEFT JOIN
     T2
     ON T1.c2 = T2.c2 AND T1.c1 = T2.c1  AND T1.c3 = 1
WHERE T1.c1 = 123
UNION 
SELECT T2.Entity1Id, T1.Entity1Id  
FROM T2 LEFT JOIN
     T1
     ON T1.c2 = T2.c2 AND T1.c1 = T2.c1  AND T1.c3 = 1
WHERE T2.c1 = 123

有时,单独子查询的优化比 full outer join 的优化要好得多。