如何优化涉及内连接的条件子选择?

时间:2013-03-14 10:50:24

标签: sql-server-2008 join query-optimization subquery commutativity

我有一个SQL查询(MS SQL 2008),我想快速优化。它具有以下结构(实际上在case语句中有10个不同的when-cases)。

重要的位是case语句中的子选择,它涉及附加表之间的内部连接和对FROM子句(table1)中某个表的引用。

我想我可以使用FROM子句中的左(外)连接而不是sub select来优化它,但我不确定,因为子选择也涉及内部连接。然后我会在FROM子句中使用两个左连接,现在我在子选择中使用内连接吗?那么在第二种情况下,它如何与AnotherTable3一起使用?

非常感谢任何想法。

    SELECT table1.a,
           table2.b,
           CASE
             WHEN table1.XY = 1 THEN
               (SELECT something
                FROM   AnotherTable1 at1
                       INNER JOIN AnotherTable2 at2
                               ON at1.x = at2.y
                WHERE  at1.abc = table2.abc)
             WHEN table1.XY = 2 THEN
               (SELECT something
                FROM   AnotherTable1 at1
                       INNER JOIN AnotherTable3 at3
                               ON at1.x = at3.y
                WHERE  at1.abc = table2.abc)
           END AS [problem]
    FROM   MyTable1 table1
           INNER JOIN MyTable2 table2
                   ON table1.a = table2.b 

2 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

SELECT 
    table1.a,
    table2.b,
    CASE 
        WHEN table1.XY = 1 THEN at2.something
        WHEN table1.XY = 2 THEN at3.something
    END
FROM   MyTable1 table1
INNER JOIN MyTable2 table2
    ON table1.a = table2.b 
LEFT JOIN AnotherTable1 at1
    ON at1.abc = table2.abc
INNER JOIN AnotherTable2 at2
    ON at1.x = at2.y
INNER JOIN AnotherTable3 at3
    ON at1.x = at3.y

但是检查结果时,还要记住at2和at3列必须具有相同的数据类型

答案 1 :(得分:0)

在这种特殊情况下,当具有相同条件的部件只需要三个左连接时,AnotherTable1连接在一起:

SELECT table1.a,
       table2.b,
       CASE
         WHEN table1.XY = 1 THEN
           ?.something -- from whereever it's coming
         WHEN table1.XY = 2 THEN
           ?.something -- from whereever it's coming
       END AS [problem]
FROM   MyTable1 table1
       INNER JOIN MyTable2 table2
               ON table1.a = table2.b 
       LEFT JOIN AnotherTable1 at1
               ON at1.abc = table2.abc
       LEFT JOIN AnotherTable2 at2
               ON at1.x = at2.y
       LEFT JOIN AnotherTable3 at3
               ON at1.x = at3.y

在更一般的情况下,你会有这个选项

FROM   MyTable1 table1
       INNER JOIN MyTable2 table2
               ON table1.a = table2.b 
       LEFT JOIN 
            (select *
               from AnotherTable1 at1
              INNER JOIN
                    AnotherTable2 at2
                      ON at1.x = at2.y   
            ) at1
               ON at1.abc = table2.abc
       ...