Mysql的Join语句中On和Where条件的区别
首先创建两张测试用表
create table t1 (id int not null,c1 int,primary key(id))
create table t2 like t1
插入如下的数据
t1
id | c1 |
---|---|
1 | 10 |
2 | 20 |
3 | 30 |
t2
id | c1 |
---|---|
1 | 10 |
2 | 40 |
3 | 50 |
执行以下的两条语句
1.条件在on后面
select * from t1 left join t2 on t1.id=t2.id and t1.c1=t2.c1
结果如下:
id | c1 | id | c2 |
---|---|---|---|
1 | 10 | 1 | 10 |
2 | 20 | NULL | NULL |
3 | 30 | NULL | NULL |
2.条件在where后面
select * from t1 left join t2 on t1.id=t2.id where t1.c1=t2.c1
结果如下:
id | c1 | id | c2 |
---|---|---|---|
1 | 10 | 1 | 10 |
结论:
left join中(right join同理)跟在on后面的条件并不会过滤左表,最终的结果一定包括左表的数据,但是会过滤右表的数据。而where后的条件,是在join的结果后进行过滤。