一、概述
left (outer) join :左连接或左外连接,把left join左边的表的记录全部找出来。系统会先用表A和表B做个笛卡儿积,然后以表A为基表,去掉笛卡儿积中表A部分为NULL的记录,最后输出结果。 双表连接条件写在on后,进行左连接时,涉及到主表、辅表,这时主表条件写在where之后,辅表条件写在and后面。
二、实例
1、表test_01,test_02结构和数据
test_01表:id和type两个字段
test_02表:id和type两个字段
2、SQL语句调用
select a.*, b.* from test_01 as a left join test_02 as b on a.id = b.id and a.type = 1;
a.id a.type b.id b.type
2 1 2 2
3 2 NULL NULL
1 1 1 1
select a.*, b.* from test_01 as a left join test_02 as b on a.id = b.id where a.type = 1;
a.id a.type b.id b.type
2 1 2 2
1 1 1 1
select a.*, b.* from test_01 as a left join test_02 as b on a.id = b.id and b.type = 1;
a.id a.type b.id b.type
2 1 NULL NULL
3 2 NULL NULL
1 1 1 1
select a.* from test_01 as a left join test_02 as b on a.id = b.id where b.id is null;
a.id a.type
3 2
select a.* from test_01 as a left join test_02 as b on a.id = b.id and b.id is null;
a.id a.type
2 1
3 2
1 1
4、总结:
sql1可见,left join 中左表的全部记录将全部被查询显示,and 后面的条件对它不起作用; 除非再后面再加上where来进行筛选,这就是sql2了; 由sql3可见,and后面的条件中,右表的限制条件将会起作用; 如果筛选出a表中有b表中没有的,这就是sql4了,sql5是不正确的;
|