一个多表查询的多种方法

--(1)偶的方法 

原贴地址:

http://topic.csdn.net/u/20091113/20/def54614-3035-4f7a-8958-4d77107b0515.html?72858

create table tableA
(
  ID
int,
  name
varchar(20)
)
insert into tableA select 1,'张三'
insert into tableA select 2,'李四'
insert into tableA select 3,'王五'
insert into tableA select 7,'赵六'
insert into tableA select 8,'孙七'


create table tableB
(
    ID
int,
  area
varchar(20)
)
insert into tableB select 1,'北京'
insert into tableB select 3,'上海'
insert into tableB select 4,'天津'
insert into tableB select 5,'青岛'
insert into tableB select 9,'成都'

create table tableC
(
  ID
int,
  career
varchar(20)
)
insert into tableC select 2,'学生'
insert into tableC select 3,'工人'
insert into tableC select 5,'教师'
insert into tableC select 6,'警察'
insert into tableC select 7,'医生'

;
with hgo as
(
select p.number AS ID,A.name from tableA A
right join
(
select number from master..spt_values where type='p'
) p
on p.number=A.ID where number<=
(
select max(ID)
from
(
select A.ID from tableA A
union all
select B.ID from tableB B
union all
select C.ID from tableC C
) tt)
and number>0
)
select h.*,B.area,C.career from hgo h left join tableB B
on h.ID=B.ID left join tableC C
on C.ID=h.ID
ID          name                 area                 career
----------- -------------------- -------------------- --------------------
1           张三                   北京                   NULL
2           李四                   NULL                 学生
3           王五                   上海                   工人
4           NULL                 天津                   NULL
5           NULL                 青岛                   教师
6           NULL                 NULL                 警察
7           赵六                   NULL                 医生
8           孙七                   NULL                 NULL
9           NULL                 成都                   NULL

--(2)下面是不逆的方法

 

 

select ID=isnull(TA.ID,isnull(TB.ID,TC.ID)),
   
[name]=max(name),
   
[area]=max(area),
   
[career]=max(career)
from [TA] full join TB on TA.ID=TB.ID  full join TC ON TB.ID=TC.ID
group by isnull(TA.ID,isnull(TB.ID,TC.ID))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值