使用组合WHERE子句的查询比两个单独的WHERE子句慢

时间:2015-11-16 14:20:50

标签: sql sql-server query-optimization

我遇到了.NET应用程序生成的SQL查询的性能问题。

基本上查询的作用是: (query1)left join(query2)right join(queries3 to 30)WHERE(query1.ID IS NULL)OR(query3.ID IS NULL AND query4.ID IS NULL AND ... queryN.ID IS NULL)

  • 当查询只执行WHERE A(query1.ID)时,查询速度很快。
  • 当查询仅执行WHERE B(查询3到30)时,查询很快
  • 当A和B是带有OR的组合WHERE子句时,查询是 很慢。

我正在寻找一种在没有变量或存储过程的情况下优化此查询的方法。

查询:

SELECT DISTINCT [Table0].[FIELD]
FROM   /*8*/ ([Table0] AS [Table0]
        INNER JOIN
        [XTABLE] AS [XTABLE0]
        ON [Table0].ID = [XTABLE0].ID1
           AND [XTABLE0].ID3 = 52)
       RIGHT OUTER /*10*/ JOIN
       [Table1] AS [Table1]
       /*21*/ /*11*/ ON [XTABLE0].ID2 = [Table1].ID
          AND [XTABLE0].ID3 = 52
       LEFT OUTER JOIN
       ([XTABLE] AS [XTABLE1]
        INNER JOIN
        [Table2] AS [Table2]
        ON [XTABLE1].ID1 = [Table2].ID
           AND [XTABLE1].ID3 = 19
        /*20a*/ INNER JOIN
        [XTABLE] AS [XTABLE2]
        ON [Table2].ID = [XTABLE2].ID1
           AND [XTABLE2].ID3 = 8
        INNER JOIN
        [Table3] AS [Table3]
        ON [XTABLE2].ID2 = [Table3].ID
           AND [XTABLE2].ID3 = 8/*22*/ )
       ON [Table1].ID = [XTABLE1].ID2
          AND [XTABLE1].ID3 = 19
       /*26 */ LEFT OUTER JOIN
       ([XTABLE] AS [XTABLE3]
        ... and tens of similar INNER JOIN blocks
WHERE  (/*13*/ [XTABLE0].ID IS NULL)
       OR (/*25*/ [XTABLE1].ID IS NULL
           AND /*27b*/ [XTABLE3].ID IS NULL
           AND /*27b*/ [XTABLE5].ID IS NULL
          ... and tens of similar lines
           AND /*27b*/ [XTABLE131].ID IS NULL);

1 个答案:

答案 0 :(得分:0)

你是外部加入查询,所以,当你从OUTER JOIN表表达式的结果(本例中是派生表)开始把东西放在WHERE子句中时,它很可能会被视为内部联接 - 您可以通过查看查询计划来查看。