数据库内连接、外连接与自连接

1、内连接:

所有满足条件的记录才会出现在结果中。

select emp.name,dept.addr from emp,dept where emp.deptid=dept.id

->

select emp.name dept.addr from emp inner join dept on emp.deptid=dept.id

内连接上述两种写法都是可以的。其中第二种是正规写法。

上面的sql是等值连接。除等值连接之外,还有非等值连接。

2、外连接:

不满足条件的记录也可以出现在结果中。其中左连接表示左边的表的记录全部都要出现在结果中,无论是否满足条件;右连接表示右侧的表的记录全部都要出现在结果中。

mysql不支持full join。支持left join和right join。所以用left join的结果union all 上right join的结果,就可以模拟full join的结果。

左侧的表称为主表,右侧的表称为从表。

外连接中,主表的所有记录都会显示出来。

3、自连接:

自连接是说一个表,连接到自己。

select t1.name as '当前类别',t2.name as '父类别'

from tree t1 left join tree t2 on t1.pid=t2.id

上面的这个例子就是自连接。

posted on 2017-12-14 16:34  刘艺LiuYi  阅读(1876)  评论(0编辑  收藏  举报

导航