实例演示 多表关联之left join

标签:
sqlleftjoin详解实例 |
分类: IT技术 |
创建4张表a,b,c,d
4张表结构相同,a(id integer, n varchar2(10))
其中表的数据记录如下:
http://s9/mw690/001sIItLgy6JP7Csqow38&690多表关联之left
不同的查询,关联方式,查询的结果是不同的
第一种
select a.id, a.n a, b.n b, c.n c
结果:
http://s12/mw690/001sIItLgy6JP7MyQYzcb&690多表关联之left
第二种
select a.id, a.n a, b.n b, c.n c
结果:
http://s15/mw690/001sIItLgy6JP7Wecwu9e&690多表关联之left
可见,对应C表中的id=5的数据没有查询出来,因为b中没有。
第三种:带等值连接的
select a.id, a.n a, b.n b, c.n c, d.n d
结果:
http://s2/mw690/001sIItLgy6JP86REGdd1&690多表关联之left
第四种:
select a.id, a.n a, b.n b, c.n c, d.n d
结果:
http://s3/mw690/001sIItLgy6JP8fg1Gif2&690多表关联之left
相比前一种,少了id=2的记录,因为C中没有id=2的记录
总结:
1、结果与关联的表及字段有关,与关联关系出现在sql中的顺序无关。
2、对于非等值连接,针对右表的限制条件应该紧随left join给出。
on a.id = b.id and
b.xx=xxx...
测试发现,上面的例子跟下面的这个sql相同:
on a.id = b.id
where b.xx=xxx...
实际工作中遇到的一个例子
select r.unit_id bd_unit_id,
追加:
以第一种写法为例,假如如下:
select a.id, a.n a, b.n b
from tmp_1 a
left join tmp_2 b
on a.id = b.id
where b.id=...
此时SQL将正常工作,不同的时,只有表B中有的记录才会被显示出来,若B表中没有或者不符合表B的条件,则不会有任何记录。
上面的sql应该相当于:
select a.id, a.n a, b.n b
from tmp_1 a
left join tmp_2 b
on a.id = b.id
and b.id=...