简体   繁体   English

oracle sql自联接过滤器在join子句vs where子句中

[英]oracle sql self-join filter in the join clause vs where clause

Suppose I have a table 假设我有一张桌子

 Table A
 ---------------
 id    date_id (yyyyMMdd format)
 ---------------
 1     20120101
 2     20120102
 3     20120103

What is the difference between doing: 做的有什么区别:

 select a1.* from A a1
 left outer join A a2
     on a1.id = a2.id 
     and a1.date_id < a2.date_id
 where a1.date >= 20120103
 and a2.id is null

And

 select a1.* from A a1
 left outer join A a2
      on a1.id = a2.id
      and a1.date_id < a2.date_id
      and a1.date_id >=20120103
 where a2.id is null

For the first query I get 对于我得到的第一个查询

 id   date_id
 --------------
 3    20120103

As expected, but for the second one I get (a2 columns not selected in query but shown here for clarity) 正如预期的那样,但是对于我得到的第二个(在查询中没有选择a2列,但为了清楚起见,这里显示)

 a1.id   a1.date_id  a2.id   a2.date_id
 ---------------------------------------
 1       20120101    
 1       20120101    
 2       20120102
 2       20120102
 3       20120103

Shouldn't the second query also filter by a1.date_id >= 20120103 ? 不应该第二个查询也按a1.date_id >= 20120103过滤? Why is it returning rows with date_id's 20120101 and 20120102 ? 为什么它返回date_id的20120101 and 20120102

In the case of outer join, ON clause will have no effect on outer table. 在外连接的情况下, ON子句对外表没有影响。 This means that all rows from outer table will be returned and ON clause just determine which row of a joined table joins outer table. 这意味着将返回外部表中的所有行,并且ON子句仅确定连接表的哪一行连接外部表。 And those rows of outer table that do not meet condition(s) in the ON clause simply will be extended with null values for columns of the table that is being joined. 并且那些不满足ON子句中的条件的外部表行将简单地使用空值扩展为正在连接的表的列。 WHERE clause filters the final result set. WHERE子句过滤最终结果集。

In the first query, it will first fetch the result set of on 在第一个查询中,它将首先获取on的结果集

a1.id = a2.id 
     and a1.date_id < a2.date_id and then it will apply the `where clause` in the result set and so you get '20120103'.

In the second query you are taking all the records that satisfy 在第二个查询中,您将获取满足的所有记录

on a1.id = a2.id
      and a1.date_id < a2.date_id
      and a1.date_id >=20120103

and thats why you get those many rows. 这就是为什么你得到那么多行。 Hope this helps you. 希望这对你有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM