简体   繁体   English

SQL Server中的查询优化

[英]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)

Above query is taking 12 seconds in SQL Server 2014, any idea to tune the query? 上面的查询在SQL Server 2014中耗时12秒,您有什么想法可以调整查询? There are indexes on C1,C2,C3 columns. 在C1,C2,C3列上有索引。

Observation: in the above query, when I remove a condition from OR (ie 观察:在上面的查询中,当我从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)

then it's returning results in 0 seconds. 然后在0秒内返回结果。

Each table has around 500'000 records. 每个表有大约500'000条记录。

First, the final condition (T1.c3 = 1 OR T1.c3 IS NULL) is redundant. 首先,最终条件(T1.c3 = 1 OR T1.c3 IS NULL)是多余的。 Given the join condition, these are the only possible values. 给定join条件,这些是唯一可能的值。 So, the query is: 因此,查询为:

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)

If this doesn't have good performance, consider breaking this into two queries: 如果这样做的性能不好,请考虑将其分为两个查询:

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

Sometimes, the optimization of the separate subqueries is much better than the optimization for the full outer join . 有时,单独子查询的优化要比full outer join的优化好得多。

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

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