@
zhangysh1995 #13
你说“WHERE 和 ON 在 JOIN 情况下没有什么区别”,你是说 inner join 吗?如果是的话,你说得没错,但是我想更加明确地说出,where 和 on 在 outer join 的表现是有区别的。
在“Database System Concepts 6th edition - Chapter 4 Intermediate SQL - 4.1 Join Expressions - 4.1.1 Join Conditions”中,说了“However, there are two good reasons for introducing the on condition. First, we shall see shortly that for a kind of join called an outer join, on conditions do behave in a manner different from where conditions. Second, an SQL query is often more readable by humans if the join condition is specified in the on clause and the rest of the conditions appear in the where clause.”。之后在“4.1.2 Outer Joins”中,它说“As we noted earlier, on and where behave differently for outer join. The reason for this is that outer join adds null-padded tuples only for those tuples that do not contribute to the result of the corresponding inner join. The on condition is part of the outer join specification, but a where clause is not.”。
我这里用例子演示一下 on 和 where 的区别吧。
create table t1(c1 int);
create table t2(c2 int);
insert into t1 values(1),(2),(3);
insert into t2 values(1);
select t1.*, t2.* from t1 left join t2 on t1.c1 = t2.c2; 的结果为
+------+------+
| c1 | c2 |
+------+------+
| 1 | 1 |
| 2 | NULL |
| 3 | NULL |
+------+------+
select t1.*, t2.* from t1 left join t2 on true where t1.c1 = t2.c2; 的结果为
+------+------+
| c1 | c2 |
+------+------+
| 1 | 1 |
+------+------+