当前位置: 代码迷 >> Sql Server >> 关于对内外连接的理解,来,小弟我看了整天的书,写几个小时的代码~总结出来的
  详细解决方案

关于对内外连接的理解,来,小弟我看了整天的书,写几个小时的代码~总结出来的

热度:422   发布时间:2016-04-27 20:37:56.0
关于对内外连接的理解,高手进来,我看了整天的书,写几个小时的代码~总结出来的
1、内连接
select   *
from   a   inner   join   b
on   a.id=b.id
等价于
select   *
from   a
where   a.id   in(select   id   from   b)
union
select   *
from   b
where   b.id   in(select   id   from   a)
也等价于
select   *
from   a,b
where   a.id=b.id
2、左连接
select   *
from   a   left   join   b
on   a.id=b.id
等价于
select   *
from   a
union
select   *  
from   b
where   b.id   in   (select   id   from   a)

3、右连接
select   *  
from   a   right   join   b
on   a.id=b.id
等价于
select   *
from   a
where   id   in   (select   id   from   b)
union
select   *
from   b

我这样的理解正确吗?

------解决方案--------------------
好象有点问题:

1、内连接
select *
from a inner join b
on a.id=b.id
不等价于
select *
from a
where a.id in(select id from b)
union
select *
from b
where b.id in(select id from a)
也等价于
select *
from a,b
where a.id=b.id

--内连接:就是相当与从a,b的id条件中找出相同的,然后连接起来。你可以从结果集中看出点什么的。

2、左连接
select *
from a left join b
on a.id=b.id
不等价于
select *
from a
union
select *
from b
where b.id in (select id from a)

--这个你理解的,好象是的对的,但是表达却错了。因为左连接的结果集是根据a表做为基础,然后找寻b的id相同的数据,没有的话,就是使用空来表示。
还是老话:看查询结果。

3、右连接
select *
from a right join b
on a.id=b.id
等价于
select *
from a
where id in (select id from b)
union
select *
from b
--如上。
------解决方案--------------------
select *
from a inner join b
on a.id=b.id
等价于
select *
from a,b
where a.id=b.id
除了这个正确以外,其它都不对,但从数据量上(行)来说又都是对
join是横联,union 是纵联,显然不一样
  相关解决方案