1

我不太确定如何描述这一点,也不太确定它是否只是语法糖。这是我第一次看到它,我很难找到关于它的原因和内容的参考或解释。

我有一个查询如下:

select * from
     table1
          join table2 on field1 = field2
          join (
               table3 
                    join table4 on field3 = field4
                    join table5 on field5 = field6
               ) on field3 = field2 
               -- notice the fields in the parens and outside the parens 
               -- are part of the on clause

括号是必要的吗?删除它们会改变加入顺序吗?在这种情况下,我处于 ​​SQL Server 2005 环境中。谢谢!

4

3 回答 3

3

使用自然连接(列顺序之外)的查询结果集的连接顺序应该没有区别。查询

select *
from t1
join t2 on t2.t1_id = t1.id

产生相同的结果集

select * from t2 join t1 on t1.id = t2.t1_id

如果您使用外连接并在 from 子句中更改表的顺序,自然外连接的方向必须改变:

select *
from      t1
left join t2 on t2.t1_id = t1.id

是相同的

select *
from       t2
right join t1 on t1.id = t2.t1_id

但是,如果您看到用作表的子查询,其语法类似于

select *
from t1
join ( select t2.*
       from t2
       join t3 on t3.t2_id = t2.id
       where t3.foobar = 37
     ) x on x.t1_id = t1.id

您会注意到x分配给上述子查询的表别名 ( )。

您所拥有的是一种称为 派生表的东西(尽管有些人称其为虚拟表)。您可以将其视为在查询生命周期中存在的临时视图。当您需要根据聚合结果 ( group by) 过滤某些内容时,它特别有用。

子句select下的 ,上的 T-SQL 文档详细介绍:from

于 2012-08-27T16:19:05.217 回答
2

在这种情况下,它们不是必需的:

select * from table1
join table2 on field1 = field2
join table3 on field3 = field2 
join table4 on field3 = field4
join table5 on field5 = field6

产生相同的结果。

于 2012-08-27T15:56:56.443 回答
2

It's not necessary in this case.

It's necessary (or at the very least, a lot simpler) in some others, especially where you name the nested call:

select table1.fieldX, table2.fieldY, sq.field6 from
table1 join table2 on field1 = field2
join ( select
   top 1 table3.field6
   from table3 join table4
   on field3 = field4
   where table3.field7 = table2.field8
   order by fieldGoshIveUsedALotOfFieldsAlready
           ) sq on sq.field6 = field12345

The code you had could have been:

  1. Like the above once, and then refactored.
  2. Machine produced.
  3. Reflecting the thought process of the developer as he or she arrived at the query, as they thought of that part of the larger query as a unit, then worked it into the larger query.
于 2012-08-27T15:59:56.073 回答