1

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

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

我在想我可以在 FROM 子句中使用左(外部)连接而不是子选择来优化它,但我不确定,因为子选择也涉及内部连接。然后我会在 FROM 子句中使用两个左连接,现在我在子选择中使用内部连接吗?从第二个 when-case 开始,这将如何与 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 
4

2 回答 2

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 列必须具有相同的数据类型

于 2013-03-14T11:08:27.563 回答
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
       ...
于 2013-03-14T11:16:03.380 回答