SQL - 连接多个表,只有一个小问题

时间:2012-02-24 18:57:42

标签: sql join multiple-tables

如果已经提出并回答了这个特定问题,我提前道歉......使用JOIN命令有很多不同的特定方式,很难找到给定问题的确切答案。我是一个SQL新手,所以...如果解决方案存在,请随时指出它。

我正在尝试加入3个不同的表,我相信我想要的东西相当于所有3个表上的FULL OUTER JOIN(MySQL不支持,据我所知)。考虑一个有3个圆圈的维恩图;我想要所有3个圆的完全并集,包括完整的交集,所有三个成对的连接(其中一个表返回NULL),以及所有三个单个实例(其中两个表返回NULL)。我相信我在这里所做的一切都会奏效,但这是一种蛮力,我相信有一种更有效的方法。我也有点担心我使用WHERE NOT EXISTS,所以请在必要时纠正我。这是我的代码的要点:


    // Intersection of all three tables
    SELECT [table1.cols], [table2.cols], [table3.cols]
        FROM table1
            INNER JOIN table2
                ON table1.col1 = table2.col1
            INNER JOIN table3
                ON table1.col1 = table3.col1

    UNION ALL

    // Intersection of tables one and two
    SELECT [table1.cols], [table2.cols], [NULLS]
        FROM table1
            INNER JOIN table2
                ON table1.col1 = table2.col1
                    WHERE NOT EXISTS (table1.col1 = table3.col1)

    UNION ALL

    // Intersection of tables two and three
    SELECT [NULLS], [table2.cols], [table3.cols]
        FROM table2
            INNER JOIN table3
                ON table2.col1 = table3.col1
                    WHERE NOT EXISTS (table2.col1 = table1.col1)

    UNION ALL

    // Intersection of tables three and one
    SELECT [table1.cols], [NULLS], [table3.cols]
        FROM table3
            INNER JOIN table1
                ON table3.col1 = table1.col1
                    WHERE NOT EXISTS (table3.col1 = table2.col1)

    UNION ALL

    // Only in table one
    SELECT [table1.cols], [NULLS], [NULLS]
        FROM table1
            WHERE NOT EXISTS ((table1.col1 = table2.col1))
            AND NOT EXISTS ((table1.col1 = table3.col1))

    UNION ALL

    // Only in table two
    SELECT [NULLS], [table2.cols], [NULLS]
        FROM table2
            WHERE NOT EXISTS ((table2.col1 = table1.col1))
            AND NOT EXISTS ((table2.col1 = table3.col1))

    UNION ALL

    // Only in table three
    SELECT [NULLS], [NULLS], [table3.cols]
        FROM table3
            WHERE (NOT EXISTS (table3.col1 = table1.col1))
            AND (NOT EXISTS (table3.col1 = table2.col1))

TIA的帮助和你的恩典。 :)

1 个答案:

答案 0 :(得分:1)

为了模拟你的完整外连接,我会预先查询你正在预期的唯一ID,然后互相LEFT JOIN ......

select
      AllPossibleKeys.CommonID,
      T1a.*,
      T2a.*,
      T3a.*
   from
      ( select distinct T1.col1 as CommonID
           from table1 T1
        UNION
        select distinct T2.col1 as CommonID
           from table2 T2
        UNION
        select distinct T3.col1 as CommonID
           from table1 T3 ) as AllPossibleKeys

      LEFT JOIN table1 T1a
         on AllPossibleKeys.CommonID = T1a.col1

      LEFT JOIN table2 T2a
         on AllPossibleKeys.CommonID = T2a.col1

      LEFT JOIN table3 T3a
         on AllPossibleKeys.CommonID = T3a.col1