如何根据SQL中的层次结构更新表列 [英] How update a table column as per hierarchy in SQL

查看:95
本文介绍了如何根据SQL中的层次结构更新表列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有以下数据,我们假设父节点Id = Parent_Id,所以有三个顶级父母(1,5,7)。



 Id Parent_Id Title 
1 1 Parent1
2 1
3 2
5 5 Parent2
6 5
7 7 Parent3
8 7
9 8





我想将结果更新到父节点的所有后代,结果应该是下面。



 Id Parent_Id Title 
1 1 Parent1
2 1 Parent1
3 2 Parent1
5 5 Parent2
6 5 Parent2
7 7 Parent3
8 7 Parent3
9 8 Parent3





我尝试了什么:



我能够将父母更新为它的直接孩子,所以我无法更新3级瓷砖。



请建议如何继续。

解决方案

你的3级项目不是父项的直接子项,因此它们不会随查询一起更新。

 Id Parent_Id Title 
1 1 Parent1
2 1 // 1的孩子(Parent1)
3 2 // 2岁的孩子,1的孙子(Parent1)
5 5 Parent2
6 5 // 5岁的孩子(Parent2) )
7 7 Parent3
8 7 // 7岁的孩子(Parent3)
9 8 // 8岁的孩子,7岁的孙子(Parent3)

你需要为孙子孙女运行第二个查询以匹配父母,这样的事情应该让你开始

 更新 t1 
SET t1.Title = t2.Title
FROM HierarchyTable t1
INNER JOIN HierarchTable t2 ON t1.Parent_Id = t2.Id


Hi I have data as below and we are assuming parent node where Id=Parent_Id, so there are three top parents(1,5,7).

Id	Parent_Id	Title
1	1	Parent1
2	1	
3	2	
5	5	Parent2
6	5	
7	7	Parent3
8	7	
9	8	



I want to update result to all descendants of parent node and the result should be as below.

Id	Parent_Id	Title
1	1	Parent1
2	1	Parent1
3	2	Parent1
5	5	Parent2
6	5	Parent2
7	7	Parent3
8	7	Parent3
9	8	Parent3



What I have tried:

I am able to update parent to it's immediate child, so i am unable to update tile of level 3.

Please suggest how to proceed.

解决方案

Your "level 3" items are not immediate children of the parent, so they will not update with the query.

Id	Parent_Id	Title
1	1	Parent1
2	1	// Child of 1 (Parent1)
3	2	// Child of 2, grandchild of 1 (Parent1)
5	5	Parent2
6	5	// Child of 5 (Parent2)
7	7	Parent3
8	7	// Child of 7 (Parent3)
9	8	// Child of 8, grandchild of 7 (Parent3)

You will need to run a second query for the grandchildren to match the parents, something like this should get you started

UPDATE t1
SET    t1.Title = t2.Title
FROM   HierarchyTable    t1
INNER JOIN HierarchTable t2 ON t1.Parent_Id = t2.Id


这篇关于如何根据SQL中的层次结构更新表列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆