如何使用hierarchyid sql显示所有递归结果
我有一个表 categories
:
ID | NAME | PARENT ID | POSITION | LEVEL | ORDER
----------------------------------------------------------------------------
1 | root | -1 | 0x | 0 | 255
2 | cars | 1 | 0x58 | 1 | 10
5 | trucks | 1 | 0x68 | 1 | 10
13 | city cars | 2 | 0x5AC0 | 2 | 255
14 | offroad cars | 2 | 0x5B40 | 2 | 255
其中:
ID int ident
NAME nvarchar(255)
PARENT ID int
POSITION hierarchyid
LEVEL hierarchyid GetLevel()
ORDER tinyint
此表 model
指定模型名称及其所属类别。示例:
ID | NAME | CATEGORY
-----------------------------
1 | Civic | 13
2 | Pajero | 14
3 | 815 | 5
4 | Avensis | 13
其中:
ID int ident
NAME nvarchar(255)
CATEGORY int link to ID category table
我想要做的是能够显示:
- 所有模型 - 将递归地显示根目录中的所有模型,
- 类别
汽车
(包括汽车)中的 - 模型来自城市汽车(或其孩子(如果有的话)
如何使用hierarchyid进行此类过滤以及如何将结果表与模型连接起来?这是显示特定级别的所有模型结果的快速方法吗?
I have a table categories
:
ID | NAME | PARENT ID | POSITION | LEVEL | ORDER
----------------------------------------------------------------------------
1 | root | -1 | 0x | 0 | 255
2 | cars | 1 | 0x58 | 1 | 10
5 | trucks | 1 | 0x68 | 1 | 10
13 | city cars | 2 | 0x5AC0 | 2 | 255
14 | offroad cars | 2 | 0x5B40 | 2 | 255
where:
ID int ident
NAME nvarchar(255)
PARENT ID int
POSITION hierarchyid
LEVEL hierarchyid GetLevel()
ORDER tinyint
This table model
specifies model name and category where it belongs. Example:
ID | NAME | CATEGORY
-----------------------------
1 | Civic | 13
2 | Pajero | 14
3 | 815 | 5
4 | Avensis | 13
where:
ID int ident
NAME nvarchar(255)
CATEGORY int link to ID category table
What I am trying to do is to be able to show:
- all models - would show all models from root recursively,
- models within category
cars
(cars included) - models from city cars (or its children if any)
How do I use hierarchyid for such filtering and how to join the table for results with models? Is that a quick way how to show all model results from certain level?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信这会给您所寻找的内容:
有关
IsDescendantOf
方法和其他hierarchyid
方法的更多信息,请检查 方法参考。I believe this would have given you what you were looking for:
For more information on the
IsDescendantOf
method and otherhierarchyid
methods, check the method reference.您需要使用 CTE:通用表表达式
https://web.archive.org/web/20210927200924/http://www.4guysfromrolla.com/webtech/071906-1.shtml
在SQL 2005中引入,允许一种简单的方法建立层次结构或递归关系。
这与您的示例非常接近:
http://www .sqlservercurry.com/2009/06/simple-family-tree-query-using.html
You going to want to use a CTE: Common Table Expression
https://web.archive.org/web/20210927200924/http://www.4guysfromrolla.com/webtech/071906-1.shtml
Introduced in SQL 2005 the allow for an easy way to do hierarchic or recursive relationships.
This is pretty close to your example:
http://www.sqlservercurry.com/2009/06/simple-family-tree-query-using.html