假设我有一张桌子
Table A
---------------
id date_id (yyyyMMdd format)
---------------
1 20120101
2 20120102
3 20120103
做什么之间有什么区别:
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
并且
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
我得到的第一个查询
id date_id
--------------
3 20120103
正如预期的那样,但我得到的第二个(在查询中没有选择a2列,但为了清楚起见,这里显示)
a1.id a1.date_id a2.id a2.date_id
---------------------------------------
1 20120101
1 20120101
2 20120102
2 20120102
3 20120103
第二个查询是否也应按a1.date_id >= 20120103
过滤?为什么返回包含date_id的20120101 and 20120102
?
答案 0 :(得分:1)
在外连接的情况下,ON
子句对外表没有影响。这意味着将返回外部表中的所有行,并且ON
子句仅确定连接表的哪一行连接外部表。并且那些不满足ON
子句中的条件的外部表行将简单地使用空值来扩展正在连接的表的列。 WHERE
子句过滤最终结果集。
答案 1 :(得分:0)
在第一个查询中,它将首先获取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'.
在第二个查询中,您将获取满足
的所有记录on a1.id = a2.id
and a1.date_id < a2.date_id
and a1.date_id >=20120103
这就是为什么你会得到那么多行。希望这会对你有所帮助。