1

速度を最適化したい SQL クエリ (MS SQL 2008) があります。次のような構造になっています (実際には、case ステートメントに 10 個の異なる when-case があります)。

重要なビットは、追加のテーブル間の内部結合と、FROM 句 (table1) 内のテーブルの 1 つへの参照を含む、case ステートメントのサブ選択です。

サブ選択の代わりに FROM 句で左 (外部) 結合を使用してこれを最適化できると考えていましたが、サブ選択には内部結合も含まれているため、確信が持てません。次に、サブ選択で内部結合を使用している FROM 句で 2 つの左結合を使用しますか? そして、それは 2 番目の 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 が両方で結合され、同じ条件のパーツが 3 つの左結合だけで済みます。

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 に答える