Note that there are some explanatory texts on larger screens.

plurals
  1. POHandling Hierarchy Data in Database
    primarykey
    data
    text
    <p>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.</p> <p><strong>Node Table</strong></p> <pre><code>NodeId int PRIMARY KEY NodeParentId int NULL DisplaySeq int NOT NULL Title nvarchar(255) </code></pre> <p><strong>Ancestor Table</strong></p> <pre><code>NodeId int AncestorId int Hops int </code></pre> <p>with Indexes on NodeId, AncestorId, Hops</p> <p>Tables look like this:</p> <p><strong>Node Table</strong></p> <pre><code>NodeId NodeParentId DisplaySeq Title 1 NULL 1 'Root' 2 1 1 'Child 1' 3 1 2 'Child 2' 4 2 1 'Grandchild 1' 5 2 2 'Grandchild 2' </code></pre> <p><strong>Ancestor Table</strong></p> <pre><code>NodeId AncestorId Hops 1 NULL 0 1 1 0 2 1 1 2 2 0 3 1 1 3 3 0 4 1 2 4 2 1 4 4 0 5 1 2 5 2 1 5 5 0 </code></pre> <p>With this design, I've found that with large hierarchies I can get an entire section of the hierarchy very quickly by joining on the Ancestor table for AncestorId = target NodeId, like:</p> <pre><code>SELECT * FROM Node n INNER JOIN Ancestor a on a.NodeId=n.NodeId WHERE a.AncestorId = @TargetNodeId </code></pre> <p>It's also easy to get direct children as well</p> <pre><code>SELECT * FROM Node n INNER JOIN Ancestor a on a.NodeId=n.NodeId WHERE a.AncestorId = @TargetNodeId AND Hops = 1 </code></pre> <p>I'm interested in knowing what other solutions you may have used for this type of thing. In my experience, hierarchies can get pretty hairy, and any way to optimize their retrieval is very important.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload