SQL连接两个ON子句(嵌套连接?)

时间:2017-10-03 13:54:58

标签: sql sql-server join syntax

我正在调试由其他人创建的报告,它具有以下加入条件。 (我已根据自己的喜好进行了布局并匿名表格名称)

SELECT  --columns
FROM    Table1
        JOIN Table2
        JOIN Table3
            ON Table2.pred = Table3.pred
        JOIN Table4
            ON Table2.pred = Table4.pred
        JOIN Table5
            ON Table2.pred = Table5.pred AND Table2.pred = Table5.pred AND Table3.pred = Table5.pred
        JOIN Table6
            ON Table3.pred = Table6.pred
            ON Table1.pred = Table5.pred AND Table1.pred = Table5.pred
        LEFT JOIN Table7
            ON Table5.pred = Table7.pred AND Table5.pred = Table7.pred
        LEFT JOIN Table7 AS Table7_1
            ON Table5.pred = Table7_1.pred AND Table5.pred = Table7_1.pred
WHERE   --conditions

我觉得令人困惑的是没有将Table1与表2相关联的连接,并且在连接到表6之后有两个ON子句。通常连接多个表:

FROM  Table
      JOIN Table2
          ON --criteria
      JOIN Table3
          ON --criteria
      JOIN Table4
          ON --criteria
      --etc

查询有效,但有人试图解决它正在做的事情,我很挣扎,因为我以前从未见过连接语法。

是否有人能够向我解释语法?

1 个答案:

答案 0 :(得分:4)

这是有效的语法。这是一个更简单的例子:

from t1 join
     t2 join
     t3
     on t2.? = t3.?
     on t1.? = t2.?

如果用括号写的话,那就更有意义了:

from t1 join
     (t2 join
      t3
      on t2.? = t3.?
     ) on t1.? = t2.?

虽然允许,但我强烈反对您不使用此语法。重写查询,以便joinon交错。