Handling Hierarchy Data in Database

后端 未结 6 1840
面向向阳花
面向向阳花 2021-02-03 14:05

I\'m curious to know what the best way (best practice) to handle hierarchies are in regards to database design. Here is a small example of how I usually handle them.

相关标签:
6条回答
  • 2021-02-03 14:16

    I'd definitely recommend nested sets. They are great.

    http://threebit.net/tutorials/nestedset/tutorial1.html http://www.dbmsmag.com/9603d06.html

    0 讨论(0)
  • 2021-02-03 14:17

    As MarkusQ and n8wrl have already pointed out, Joe Celko has some good stuff on this. I'll just add that there are multiple ways to model a hierarchy (Joe's book contains several I believe, not just one that he considers the "best"). Your final decision will hopefully take into account your own specific needs. Some of the different ways to model it are better for write-intensive operations while others are better for frequent or fast reads up and down the hierarchy. Just keep in mind what your system will be doing with it.

    0 讨论(0)
  • 2021-02-03 14:18

    There are some vendor-specific extensions to do this, but my favorite db-neutral way comes from Joe Celko - google 'Joe Celko Trees and Hierarchies' or buy this book: link text

    This is a very clever set-based way to go. Easy to query hierarchy. I added the 'parentID' field you have just because I ask the 'direct children' and 'parent' questions a lot and that speeds those up. But this is a wonderful way to get a 'ancestry' or 'descdent' query.

    0 讨论(0)
  • 2021-02-03 14:20

    SQL Server 2008 introduced the hierarchyid data type

    0 讨论(0)
  • 2021-02-03 14:23

    In Oracle, you can use CONNECT BY/START WITH to query hierarchial data. In SQL Server, you can use a stored procedure, that calls itself recursively.

    0 讨论(0)
  • 2021-02-03 14:29

    You may also want to check out the "nested sets" pattern:

    http://www.intelligententerprise.com/001020/celko.jhtml (Broken Link)

    Or you can Google for more.

    P.S.: Curses, n8wrl, you type faster than I do!

    0 讨论(0)
提交回复
热议问题