mysql的多表查询

转自:http://huaxia524151.iteye.com/blog/1423614

转自:http://blog.sina.com.cn/s/blog_4c197d420101cnm9.html

 

连接类型

分为三种:交叉连接(笛卡尔积)、内连接(自然连接、等值连接、非等值连接)、外连接。

 

现有表R,S如下:

表R

 

表S

 

(1)交叉连接(笛卡尔积)cross join

没有where子句的交叉连接将产生连接表的笛卡尔积。

 

例一:

select * from R cross join S;

select * from R,S;

结果:

 

注:不需要任何条件。结果为两张表函数相乘(3x3=9)。

 

例二:

select * from R cross join S where R.C = S.C;

结果:

 

(2)内连接

内连接分为三种:自然连接、等值连接、非等值连接。

 

A.自然连接 natural join:在连接条件中使用等于=运算符比较被连接列的列值,但删除连接表中重复列。

 

例一:

select * from R natural join S;

select e.empno,e.ename,m.empno,m.ename from emp e,emp m where m.mgr = e.empno; 

结果:


 B.等值连接  :使用等于=比较连接列的列值,在查询结果中列出接连表中的所有列,包括其中的重复列。

select * from R  join S where R.C = S.C;

select * from R inner join S where R.C = S.C;

结果:

 

C.非等值连接:在连接条件中,可以使用其他比较运算符,比较被连接列的列值,如:<、>、!=等。

 

(3)外连接

外连接分为三类:全外连接、左外连接、右外连接。

 

A.左外连接 left join / left outer join

select * from R left join S on R.C = S.C;

 

左外连接要遍历左表的所有记录,右表没有的用null表示。

 

B.右外连接 right join / right outer join

select * from R right join S on R.C = S.C;

 

右外连接要遍历右表所有的记录,左表没有的用null表示。

 

C.全外连接 full join / full outer join

select * from R full join S on R.C = S.C;

 

 

mysql中的全连接补充:

MySQL支持左连接,右连接,但是并不支持全连接。

通过基本是下全连接的效果。
表数据说明:

表a


表b

 

 

自然连接sql:
select a.id as a_id,a.name as a_name, b.id as b_id,b.name as b_name
from stu_a a ,stu_b b
where a.id=b.id

 

 

 

左连接sql:
select a.id as a_id,a.name as a_name, b.id as b_id,b.name as b_name
from stu_a a
left join stu_b b
on a.id=b.id


右连接sql:
select a.id as a_id,a.name as a_name, b.id as b_id,b.name as b_name
from stu_a a
right join stu_b b
on a.id=b.id

 

 

 

合并左、右连接:
select a.id as a_id,a.name as a_name, b.id as b_id,b.name as b_name
from stu_a a
left join stu_b b
on a.id=b.id
union
select a.id as a_id,a.name as a_name, b.id as b_id,b.name as b_name
from stu_a a
right join stu_b b
on a.id=b.id

 

也可以是:
select a.id as a_id,a.name as a_name, b.id as b_id,b.name as b_name
from stu_a a
left join stu_b b
on a.id=b.id
union
select a.id as a_id,a.name as a_name, b.id as b_id,b.name as b_name
from stu_a a
right join stu_b b
on a.id=b.id
where a.id is null

 

 

 

 

 

 

posted @ 2014-04-17 12:41  明明是悟空  阅读(419)  评论(0编辑  收藏  举报