SQLSERVER表联结(INNER JOIN,LEFT JOIN,RIGHT JOIN,FULL JOIN,CROSS JOIN,CROSS APPLY,OUTER APPLY)

1 常用表联结(inner join,left join,right join,full join,cross join)

if object_id(N'table1',N'U') is not null
    drop table table1
if object_id(N'table2',N'U') is not null
    drop table table2
create table table1(id int,name varchar(20))
insert into table1
select 1,'小明' union all
select 2,'小李' union all
select 3,'小陈' union all
select 4,'小吴'

create table table2(id int,age int)
insert into table2
select 1,23 union all
select 2,24 union all
select 3,25 union all
select 5,26
--连接举例
--,
select a.*,b.* from table1 a,table2 b where b.id = a.id
--cross join 交叉联接(注:cross join后加条件只能用where,不能用on)
select * from table1 a cross join table2 b where b.id = a.id
--inner join 内连接
select * from table1 a inner join table2 b on b.id = a.id
--left join 左外连接
select * from table1 a left join table2 b on b.id = a.id
--right join 右外连接
select * from table1 a right join table2 b on b.id = a.id
--full join 全外连接
select * from table1 a full join table2 b on b.id = a.id

--以下两个语句,效果相同
select * from table1 cross join table2
select * from table1,table2

--以下三个语句,效果相同
select * from table1 a,table2 b where b.id = a.id
select * from table1 a cross join table2 b where b.id = a.id
select * from table1 a inner join table2 b on b.id = a.id

2 cross apply,outer apply

(cross apply,outer apply 是SQL Server 2005 新增的)

SQL Server 2000 中有个 cross join 是用于交叉连接。

增加 cross apply 和 outer apply 是用于交叉连接表值函数。

APPLY 的两种形式:CROSS APPLY 和 OUTER APPLY。

CROSS APPLY 仅返回外部表中通过表值函数生成结果集的行。

OUTER APPLY 既返回生成结果集的行,也返回不生成结果集的行,其中表值函数生成的列中的值为 NULL。

--创建表值函数 FN_TableValue
IF object_id(N'FN_TableValue',N'TF') IS NOT NULL
DROP FUNCTION FN_TableValue
GO
create function FN_TableValue(@id varchar(100))
returns @a TABLE (
    id int,
    name varchar(10) NULL
)
AS begin
insert into @a
select * from table2 where id = @id
return
end
go

--cross apply
select *
from table1 t1
cross apply (SELECT 1 id,'test1' name UNION ALL SELECT 2,'test2') t2
where t1.id= t2.id

select * from table1
select *
from table1 T1
cross apply FN_TableValue(T1.id)

--outer apply
select *
from table1 T1
outer apply FN_TableValue(T1.id)

 

posted @ 2016-08-02 19:32  小志1236  阅读(1175)  评论(0编辑  收藏  举报