第一种写法:select A.一堆项目,
B.一堆项目
from A left join B
on A.a1 = B.b1
and B.b2=1where A.一些项目= 一些东西 and
B.一些项目= 一些东西第二种写法:select A.一堆项目,
B.一堆项目
from A left join B
on A.a1 = B.b1where A.一些项目= 一些东西 and
B.一些项目= 一些东西 and B.b2=1
B.一堆项目
from A left join B
on A.a1 = B.b1
and B.b2=1where A.一些项目= 一些东西 and
B.一些项目= 一些东西第二种写法:select A.一堆项目,
B.一堆项目
from A left join B
on A.a1 = B.b1where A.一些项目= 一些东西 and
B.一些项目= 一些东西 and B.b2=1
insert into t1 values(1 , 1);
insert into t1 values(1 , 2);
insert into t1 values(1 , 3);
insert into t1 values(1 , 4);
insert into t1 values(2 , 1);
insert into t1 values(2 , 2);
create table t2(id int, feild int);
insert into t2 values(1 , 1);
insert into t2 values(1 , 2);
insert into t2 values(1 , 5);
insert into t2 values(1 , 6);
insert into t2 values(2 , 1);
insert into t2 values(2 , 3);
select t1.*,t2.* from t1 left join t2 on t1.id=t2.id
--取t1表的第一行,扫瞄t2表,按条件做对比,如果满足条件,就加入返回结果表.
--然后取t1表的第二行,扫瞄t2表,按条件做对比,如果满足条件,就加入返回结果表.
--重复以上过程,直到t1表扫描结束.
/*
id feild id feild
1 1 1 1
1 1 1 2
1 1 1 5
1 1 1 6
1 2 1 1
1 2 1 2
1 2 1 5
1 2 1 6
1 3 1 1
1 3 1 2
1 3 1 5
1 3 1 6
1 4 1 1
1 4 1 2
1 4 1 5
1 4 1 6
2 1 2 1
2 1 2 3
2 2 2 1
2 2 2 3
*/select t1.*,t2.* from t1 left join t2 on t1.id=t2.id and t1.feild=1
--给左表加条件的时候,左表满足条件的,按上面的过程返回值,左表不满足条件的,直接输出,右表的列补null
/*
id feild id feild
1 1 1 1
1 1 1 2
1 1 1 5
1 1 1 6
1 2 NULL NULL
1 3 NULL NULL
1 4 NULL NULL
2 1 2 1
2 1 2 3
2 2 NULL NULL
*/select t1.*,t2.* from t1 left join t2 on t1.id=t2.id where t1.feild=1
--先执行where后连接查询
--执行where后表为 1 , 1
-- 2 , 1
--用它来left join t2.
/*
id feild id feild
1 1 1 1
1 1 1 2
1 1 1 5
1 1 1 6
2 1 2 1
2 1 2 3
*/
--下面三条语句查询结果是一样的,当为右表加条件的时候,可以把left join 改为inner jin, 因为inner join比left join 要快!select t1.*,t2.* from t1 left join t2 on t1.id=t2.id and t2.feild=1
select t1.*,t2.* from t1 left join t2 on t1.id=t2.id where t2.feild=1
select t1.*,t2.* from t1 inner join t2 on t1.id=t2.id and t2.feild=1/*
id feild id feild
1 1 1 1
1 2 1 1
1 3 1 1
1 4 1 1
2 1 2 1
2 2 2 1
*/drop table t1
drop table t2
select A.一堆项目,
B.一堆项目
from A inner join B
on A.a1 = B.b1
where A.一些项目= 一些东西 and
B.一些项目= 一些东西 and B.b2=1
1L测试中,发现结果有些不同!,特别是left join ,加上where =1表示非null
与应用需求有关