Managing hierarchies in SQL: MPTT/nested sets vs adjacency lists vs storing paths

旧城冷巷雨未停 提交于 2019-11-30 01:25:21
Bill Karwin

You might also consider the Closure Table design I describe in my answer to What is the most efficient/elegant way to parse a flat table into a tree?

Calls required to create/delete/move a node:

  • Closure = 1

Calls required to get a tree:

  • Closure = 1

Calls required to get path to a node / ancestry:

  • Closure = 1

Calls required to get number of subnodes:

  • Closure = 1

Calls required to get depth of node:

  • Closure = 1

DB fields required:

  • Adjancency = 1 more field / row
  • Path = 1 more field / row
  • MPTT = 2 or 3 more fields / row
  • Closure = 2 or 3 fields in extra table. This table has O(n^2) rows worst case but far fewer than that in most practical cases.

There are a couple of other considerations:

Supports unlimited depth:

  • Adjacency = yes
  • MPTT = yes
  • Path = no
  • Closure = yes

Supports referential integrity:

  • Adjacency = yes
  • MPTT = no
  • Path = no
  • Closure = yes

I also cover Closure Table in my presentation Models for Hierarchical Data with SQL and PHP, and my book, SQL Antipatterns: Avoiding the Pitfalls of Database Programming.

It problem with your conclusion is that it ignores most of the issues involved in working with trees.

By reducing the validity of a technique to the "number of calls" you effectively ignore all of the issues which well understood data structures and algorithms attempt to solve; that is, fastest execution and low memory and resource foot print.

The "number of calls" to an SQL server may seem like a good metric to use ("look ma less code"), but if the result is a program which never finishes, runs slowly, or takes up to much space, it is in fact a useless metric.

By storing the path with every node you are not creating a tree data structure. Instead you are creating a list. Any operation which a tree is designed to optimize is lost.

This might be hard to see with small date sets (and in many cases of small trees a list is better), try some examples on data sets of size 500, 1000, 10k -- You will quickly see why storing the whole path is not a good idea.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!