一个主表和三个附表的sql查询,请高手帮忙

bfzf266 2007-09-10 08:12:26
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语句要如何写出来。
...全文
247 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
dawugui 2007-09-10
  • 打赏
  • 举报
回复
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
bfzf266 2007-09-10
  • 打赏
  • 举报
回复
谢谢wangtiecheng和roy_88,大开眼界。已经解决我的问题了。
OracleRoob 2007-09-10
  • 打赏
  • 举报
回复
--借用楼上数据

declare @a table(ID int,class nvarchar(10),Name nvarchar(5))
insert @a select 1,'11','a'
insert @a select 2,'22','b'
insert @a select 3,'33','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 a.id, a.name, a.class, t.usage
from @a as 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
中国风 2007-09-10
  • 打赏
  • 举报
回复
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 行)

OracleRoob 2007-09-10
  • 打赏
  • 举报
回复
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

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧