sql语句写不出来了,救命呀!

forjie 2004-01-06 05:33:12
数据结构如下:

id 层次 parent_id
1 1
2 2
3 2
4 3
5 4
6 3
id唯一,层次说明树的结构,大数是上一条记录的子节点,怎样通过一条update语句添上parent_id变成标准树结构呀?(如下)
id 层次 parent_id
1 1 0
2 2 1
3 2 1
4 3 3
5 4 4
6 3 3


...全文
115 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 元老 2004-01-07
  • 打赏
  • 举报
回复
--下面是数据测试

--测试数据
declare @t table(id int,层次 int,parent_id int)
insert into @t(id,层次)
select 1,1
union all select 2,2
union all select 3,2
union all select 4,3
union all select 5,4
union all select 6,3

--更新处理
update @t set parent_id=case 层次 when 1 then 0
else (select top 1 id from @t where 层次=a.层次-1 and id<a.id order by id desc) end
from @t a

--显示处理结果
select * from @t

/*--测试结果
id 层次 parent_id
----------- ----------- -----------
1 1 0
2 2 1
3 2 1
4 3 3
5 4 4
6 3 3

(所影响的行数为 6 行)
--*/
zjcxc 元老 2004-01-07
  • 打赏
  • 举报
回复
--将你的查询语句照搬上去就行了嘛:

update tb1 set parent_id=case 层次 when 1 then 0
else (select top 1 id from tb1 where 层次=a.层次-1 and id<a.id order by id desc) end
from tb1 a
forjie 2004-01-07
  • 打赏
  • 举报
回复
多谢各位老大,我的语句没判断null,呵呵,晕菜了。
给分。
xhwly 2004-01-06
  • 打赏
  • 举报
回复
理解樓主的意思了。已經測試成功
update tbl set parent_id = case when (select top 1 id from tbl b where b.層次 = tbl.層次 -1 and b.id < tbl.id order by b.id desc) is null then 0
else (select top 1 id from tbl b where b.層次 = tbl.層次 -1 and b.id < tbl.id order by b.id desc) end
xhwly 2004-01-06
  • 打赏
  • 举报
回复
單從層次應該是不行的,樓主自己列的兩種树结构結果對應的層次都是一樣的。

树结构1:
1
2 3
4 6
5

树结构2:
1
2 3
4 6
5

Jianli2004 2004-01-06
  • 打赏
  • 举报
回复
while exists (...)
-狙击手- 2004-01-06
  • 打赏
  • 举报
回复
是一个部件爆炸的算法吧,但是楼主说的我还是有点不明白
forjie 2004-01-06
  • 打赏
  • 举报
回复
高手哪儿去啦?
forjie 2004-01-06
  • 打赏
  • 举报
回复
肯定可行的。
我用:
select * from tbl a
where exists (select top 1 b.id from tbl b where b.id<a.id and b.层次=a.层次-1 order by b.xh_id desc) 可以看出正确选择出了记录,
但是select * from tbl a
where a.id = (select top 1 b.id from tbl b where b.id<a.id and b.层次=a.层次-1 order by b.xh_id desc) 为什么就没有记录呢?
CSharpSky 2004-01-06
  • 打赏
  • 举报
回复
单单从层次能决定他们的父结点?
组成的可能太多了
forjie 2004-01-06
  • 打赏
  • 举报
回复
对不起,刚上面的树结构图画错了,应该是:
树结构如下:
1
2 3
4 6
5
forjie 2004-01-06
  • 打赏
  • 举报
回复
我有点思路了,但是语句总是不对,谁能帮看看吗?谢了。

update tbl
set parent_id = (select top 1 id from tbl b where b.id<id and (b.层次-1)=层次 order by b.id desc)
怎么全是null呢?

forjie 2004-01-06
  • 打赏
  • 举报
回复
就是这种bt结构呀,往上面倒退随搜,层次比当前小的第一条就是他的父项。
比如6的层次是3,往上退第一个层次是2的记录是3,所以3是6的父节点。
txlicenhe 2004-01-06
  • 打赏
  • 举报
回复
楼主给的数据没有办法得出,
比如: 你怎么知道4和6的父结点是3而不是2?
forjie 2004-01-06
  • 打赏
  • 举报
回复
树结构如下:
1
2 3
4 6
5

34,588

社区成员

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

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