单表一对多关系查询

tkdg0224 2014-06-09 11:10:04
表中用一个PID字段记录同一张表中的ID,现希望在表中查询父子记录的数据


create table #tmp(id int,pid varchar(30),Context varchar(30))
insert into #tmp
select 1, null , '1' union all
select 2, null , '2' union all
select 3, null , '3' union all
select 4, null , '4' union all
select 5, 1 , '1_1' union all
select 6, 2 , '2_1' union all
select 6, 3 , '3_1' union all
select 7, 4 , '4_1'
select * from #tmp
--下面这句显然错误
select id,Context,(select Context from #tmp where pid=id )as pContext from #tmp

DROP TABLE #tmp
...全文
151 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
tkdg0224 2014-06-09
  • 打赏
  • 举报
回复
这时想要的/* id Context pContext ----------- ------------------------------ ------------------------------ 1 1 NULL 2 2 NULL 3 3 NULL 4 4 NULL 5 1_1 1 6 2_1 2 6 3_1 3 7 4_1 4 */ 谢谢已解决 select #tmp.id,#tmp.Context,b.context as pContext from #tmp LEFT JOIN (select Context,id from #tmp ) b ON b.id= pid
exception92 2014-06-09
  • 打赏
  • 举报
回复

create table #tmp(id int,pid varchar(30),Context varchar(30))
insert into #tmp
select 1,    null ,   '1'            union all
select 2,    null ,    '2'      union all
select 3,    null ,   '3'       union all
select 4,    null ,    '4' union all
select 5,   1  ,    '1_1' union all
select 6,   2  ,    '2_1' union all
select 6,   3  ,    '3_1' union all
select 7,  4  ,    '4_1'

--下面这句显然错误
select B.id,B.Context,(select Context from  #tmp as A where A.pid=B.id )as pContext from  #tmp as B

DROP TABLE #tmp
id Context pContext 1 1 1_1 2 2 2_1 3 3 3_1 4 4 4_1 5 1_1 NULL 6 2_1 NULL 6 3_1 NULL 7 4_1 NULL
發糞塗牆 2014-06-09
  • 打赏
  • 举报
回复
你想得到这样?
create table #tmp(id int,pid varchar(30),Context varchar(30))
insert into #tmp
select 1,    null ,   '1'            union all
select 2,    null ,    '2'      union all
select 3,    null ,   '3'       union all
select 4,    null ,    '4' union all
select 5,   1  ,    '1_1' union all
select 6,   2  ,    '2_1' union all
select 6,   3  ,    '3_1' union all
select 7,  4  ,    '4_1'
select * from  #tmp
--下面这句显然错误
select id,#tmp.Context,b.context  as pContext from  #tmp LEFT JOIN (select Context,pid from  #tmp ) b ON  b.pid=id 

DROP TABLE #tmp

/*
id          Context                        pContext
----------- ------------------------------ ------------------------------
1           1                              1_1
2           2                              2_1
3           3                              3_1
4           4                              4_1
5           1_1                            NULL
6           2_1                            NULL
6           3_1                            NULL
7           4_1                            NULL

*/

34,588

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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