日期:2014-05-19  浏览次数:20608 次

再问: 2个左连接的写法问题的原理
让第二个表与第三个左连接构成一个子查询,然后它与第一个表左连接
表定义:temp6(id,age),temp7(age,age2),temp8(age2,name)
temp6是主表,age是整形字段
下面是我上次问得到的答案,但有点麻烦,因为每次都要子查询
select   temp6.*,t.*   from   temp6
left   join  
(
select   temp7.*,temp8.name   from   temp7   left   join   temp8   on   temp7.age2   =   temp8.age2
)   T
on   temp6.age   =   T.age

根据上次提问的结果,可以如下写:
select   *  
from   temp6  
left   join   temp7   on   temp6.age=temp7.age
left   join   temp8   on   temp7.age=temp8.age2
虽然结果正确,内部机制我还是不太明白,只左连一个比较容易理解,左连2个,第二个是如何被附加到结果里的,今天又做了一个,子连接有2个连接字段,其中一个还要和最外层的表关联,因为对原理不明白,写得晕头转向的。
今天写的是这样的一个:
A表是主表,B表有两个主键,f1,f2,f1存在于A表,f2存在于C表,f1的值又通过参数可以得到,想把B和C左连接到A中,不知怎么写对,瞎写了一个。
select   A.*,C.*  
from   A
left   join   B   on   A.f1=B.f1
left   join   C   on   C.f2=B.f2
where  
A.f1= 'a '
现在的感觉就是乱死了,朦朦胧胧地觉得这样可能是对的,但讲不出道理,谁能解释一下内部的原理啊。谢谢谢谢


------解决方案--------------------

--查询分析器中执行:
--建表table1,table2:
create table table1(id int,name varchar(10))
create table table2(id int,score int)
insert into table1 select 1, 'lee '
insert into table1 select 2, 'zhang '
insert into table1 select 4, 'wang '
insert into table2 select 1,90
insert into table2 select 2,100
insert into table2 select 3,70
如表
-------------------------------------------------
table1|table2|
-------------------------------------------------
idname|idscore|
1lee|190|
2zhang|2100|
4wang|370|
-------------------------------------------------

以下均在查询分析器中执行

一、外连接
1.概念:包括左向外联接、右向外联接或完整外部联接

2.左连接:left join 或 left outer join
(1)左向外联接的结果集包括 LEFT OUTER 子句中指定的左表的所有行,而不仅仅是联接列所匹配的行。如果左表的某行在右表中没有匹配行,则在相关联的结果集行中右表的所有选择列表列均为空值(null)。
(2)sql语句
select * from table1 left join table2 on table1.id=table2.id
-------------结果-------------
idnameidscore
------------------------------
1lee190
2zhang2100
4wangNULLNULL
------------------------------
注释:包含table1的所有子句,根据指定条件返回table2相应的字段,不符合的以null显示

3.右连接:right join 或 right outer join
(1)右向外联接是左向外联接的反向联接。将返回右表的所有行。如果右表的某行在左表中没有匹配行,则将为左表返回空值。
(2)sql语句
select * from table1 right join table2 on table1.id=table2.id
-------------结果-------------
idnameidscore
------------------------------
1lee190
2zhang2100
NULLNULL370
------------------------------
注释:包含table2的所有子句,根据指定条件返回table1相应的字段,不符合的以null显示

4.完整外部联接:full join 或 full outer join
(1)完整外部联接返回左表和右表中的所有行。当某行在另一个表中没有匹配行时,则另一个表的选择列表列包含空值。如果表之间有匹配行,则整个结果集行包含基表的数据值。
(2)sql语句
select * from table1 full join table2 on table1.id=table2.id
-------------结果-------------
idnameidscore
------------------------------
1lee190
2zhang2100
4wangNULLNULL
NULLNULL370
------------------------------
注释:返回左右连接的和(见上左、右连接)

二、内连接
1.概念:内联接是用比较运算符比较要联接列的值的联接

2.内连接:join 或 inner join

3.sql语句
select * from table1 join table2 on table1.id=table2.id
-------------结果-------------
idnameidscore
------------------------------
1lee190
2zhang2100
------------------------------
注释:只返回符合条件的table1和table2的列

4.等价(与下列执行效果相同)
A:select a.*,b.* from table1 a,table2 b where a.id=b.id
B:select * from table1 cross join tab