日期:2014-05-18  浏览次数:20562 次

一个主表和三个附表的sql查询,请高手帮忙
a表
a.id     b.name     c.class

b表
a.id     b.usage  

c表
a.id     b.usage

d表
a.id     b.usage

a表为主表,存贮主要信息,b,c,d表为三类附属表存贮次要信息,a表中的一条记录的次要可能在b表中,可能在c表中也可能在d表中。

需要同时查出每一条记录的id和usage,请问各位大侠这个sql语句要如何写出来。

------解决方案--------------------
select a.id, a.name, a.class, t.usage
from A
left join
(
select id,usage from b
union all
select id,usage from c
union all
select id,usage from d
) as t on a.id=t.id

------解决方案--------------------
declare @a table(ID int,Name nvarchar(5))
insert @a select 1, 'a '
union all select 2, 'b '
union all select 3, 'c '

declare @b table(ID int,usage nvarchar(5))
insert @b select 1, 'aa '
declare @c table(ID int,usage nvarchar(5))
insert @c select 2, 'bb '
declare @d table(ID int,usage nvarchar(5))
insert @d select 3, 'cc '

select
*,
[usage]=isnull(isnull((select top 1 [usage] from @b where ID=a.ID),
(select top 1 [usage] from @c where ID=a.ID)),
(select top 1 [usage] from @d where ID=a.ID))

from
@a a


(所影响的行数为 3 行)


(所影响的行数为 1 行)


(所影响的行数为 1 行)


(所影响的行数为 1 行)

ID Name usage
----------- ----- -----
1 a aa
2 b bb
3 c cc

(所影响的行数为 3 行)


------解决方案--------------------
1、假设b,c,d中只有一条记录是对应A的。

select a.*,isnull(t.usage , ' ') usage from a
left join
(
select * from b
union all
select * from c
union all
select * from d
) t
on a.id = t.id

2、假设b,c,d中各有一条记录是对应A的。

select a.*,isnull(b.usage, ' ') busage,isnull(c.usage, ' ') cusage,isnull(d.usage, ' ') dusage from a
left join b on a.id = b.id
left join c on a.id = c.id
left join d on a.id = d.id