简体   繁体   English

如何在SQL数据库中存储树

[英]How to store a tree in SQL database

I have to store a tree in a database, so what is the best way to do this? 我必须在数据库中存储一棵树,那么最好的方法是什么? Show the method you use and name its pros and cons. 显示您使用的方法并命名其优缺点。 (I am using SQL Server 2005) (我使用的是SQL Server 2005)

I found the discussion in the SQL Anti-patterns very helpfull, as it also focuses on the drawbacks of every implementation. 我发现SQL反模式中的讨论非常有用,因为它还关注每个实现的缺点。

Also, The slides 48-77 in this presentation reiterate that analisys. 此外, 本演示文稿中的幻灯片48-77重申了分析。

Bottom line, there is no such thing as a generic tree, and no silver bullet for SQL trees. 最重要的是,没有通用树这样的东西,也没有SQL树的银弹。 You'll have to ask yourself about the data, how and how much will they be selected, modified, will branches be moved around, etc, and based on those answers implement a suitable solution. 您将不得不问自己关于数据,如何选择,修改,分支移动等等,并根据这些答案实施合适的解决方案。

Well, the easiest way would be for a record to have a ParentID column so that it knows which record is its parent. 嗯,最简单的方法是让记录有一个ParentID列,以便它知道哪个记录是它的父记录。 This is a pretty standard practice. 这是一个非常标准的做法。 For example, an online store might have a hierarchy of product categories. 例如,在线商店可能具有产品类别的层次结构。 Each category will have a ParentID. 每个类别都有一个ParentID。 Example: The "Jeans" category in an clothing database might have "Pants" as the parent category. 示例:服装数据库中的“牛仔裤”类别可能将“裤子”作为父类别。 It's a bit harder if you want a record to indicate which are its children, unless you restrict the number of children. 如果你想要一条记录来表明它的孩子是哪一个,那就更难了,除非你限制孩子的数量。 If you want a binary tree, you could have LeftChildID and RightChildID columns. 如果需要二叉树,可以使用LeftChildID和RightChildID列。 If you allow any number of children, you could have a Children column with IDs delimited by commas (such as 1,4,72,19 ) but that will make querying rather hard. 如果您允许任意数量的子项,则可以使用逗号分隔的ID(例如1,4,72,19 )的子列,但这会使查询变得相当困难。 If your database allows for array types in columns, you can probably use an array instead of a delimited string, which would be easy to query - but I'm not sure if MS SQL Server supports that or not. 如果您的数据库允许列中的数组类型,您可以使用数组而不是分隔字符串,这很容易查询 - 但我不确定MS SQL Server是否支持。

Other than that, it depends on what kind of data you are modelling, and also what sort of operations you plan to do with this tree. 除此之外,它取决于您正在建模的数据类型,以及您计划对此树执行的操作类型。

我过去通过在SQL中将数据存储为xml来完成此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM