在关系数据库中建模层次结构/目录

时间:2011-07-28 13:04:30

标签: mysql data-structures tree data-modeling hierarchical

我想在mysql表中建模一个层次结构/目录,如下所示。您可以在下面看到我正在考虑的表模式。 但是,Im谈论的目录将由100.000个元素组成,深度为~5-10个级别。此外,我们将有一个标签池,目录的每个元素可以链接到一个或多个标签。所以我想知道是否有更好的方法。我正在读一些人决定设计一些表格,这些表格不是规范性的,因为我们正在评估这个案例。

ps:有些人使用多向树在编程语言级别对此进行建模,因此问题如何在数据库中结束仍然存在。

hierarchy:
A
| -> 1
     |->1
     |->2
| -> 2
| -> 3
B
| -> 1
| -> 2

table:
 ___________________________
| id      |element | father |
|---------------------------|
|  000    |   A    |  null  |
|  001    |   1    |  000   |
|  002    |   1    |  001   |
|  003    |   2    |  001   |
|  004    |   2    |  000   |
|  005    |   3    |  000   |
|  006    |   B    |  null  |
|  001    |   1    |  006   |
|  002    |   2    |  006   |
-----------------------------

1 个答案:

答案 0 :(得分:5)

一个非常快速的层次树是嵌套集或Celko树,当你有一个MySQL存储引擎时,它有点像二叉树或者霍夫曼树。缺点是昂贵的删除和插入。其他RDBMS也支持递归查询。一般来说,我没有看到很多嵌套集。创建和维护似乎也很复杂。当嵌套集太复杂而RDBMS不支持递归查询时,也会有物化路径。

  1. http://www.ibase.ru/devinfo/DBMSTrees/sqltrees.html
  2. http://en.wikipedia.org/wiki/Binary_tree
  3. http://en.wikipedia.org/wiki/Huffman_coding
  4. http://www.postgresql.org/docs/8.4/static/queries-with.html
  5. Is it possible to make a recursive SQL query?
  6. http://www.cybertec.at/pgbook/node122.html