交叉连接行为(SQLServer 2008)

Mik*_*e Q 7 sql sql-server outer-join cross-join sql-server-2008

我一直试图通过我的查询来追踪问题.查询实际上是由HQL从HQL生成的,但生成的SQL没有达到我的预期.稍微修改SQL会产生正确的结果,但我不确定为什么修改应该有所不同.

原始查询(不返回任何行)

select sched.id, max(txn.dttm), acc.id
from PaymentSchedulePeriod sched 
cross join PaymentSchedulePayment pay
right outer join AccountTransaction txn on pay.accountTransactionFk=txn.id 
right outer join Account acc on txn.accountFk=acc.id 
where sched.accountFk=acc.id 
group by sched.id, acc.id
Run Code Online (Sandbox Code Playgroud)

修改后的查询 - 用逗号替换交叉连接(隐式交叉连接)

返回一行

select sched.id, max(txn.dttm), acc.id
from PaymentSchedulePeriod sched 
,PaymentSchedulePayment pay
right outer join AccountTransaction txn on pay.accountTransactionFk=txn.id 
right outer join Account acc on txn.accountFk=acc.id 
where sched.accountFk=acc.id 
group by sched.id, acc.id
Run Code Online (Sandbox Code Playgroud)

我的理解可能是不正确的,写作from Table1 a, Table2 b与写作是一样的from Table 1 a cross join Table2 b.所以我不明白为什么查询返回不同的结果.

是否与第一个查询中的交叉连接和外连接之间的交互有关?我查看了查询计划,第二个查询计划看起来很合理.第一个没有外连接,这很奇怪.

这是在SQLServer 2008上.

Joe*_*lli 9

JOIN的优先级高于COMMA,因此您的第二个语句被解释为(注意我添加的parens):

select sched.id, max(txn.dttm), acc.id
from PaymentSchedulePeriod sched 
,(PaymentSchedulePayment pay
right outer join AccountTransaction txn on pay.accountTransactionFk=txn.id 
right outer join Account acc on txn.accountFk=acc.id)
where sched.accountFk=acc.id 
group by sched.id, acc.id
Run Code Online (Sandbox Code Playgroud)

另请参阅:按SQL-99加入优先级规则