modeling hierarchy/directory in a relational database
I would like to model a hierarchy/directory like what you see below, in a mysql table. You can see below the table schema I was thinking. However, the directory Im talking about would be comprised of 100.000 elements and the depth would be ~5-10 levels. Moreover, we will have a tags pool and each element of the directory may be linked to one or more tags. So I was wondering if there is better approach. I was reading that some people decide to design tables that are not canonical for the shake of high performance and I am evaluating this case too.
ps: some people use Multi-way Trees to model this in the programming language level so the question how this ends up in the database remains.
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 |
-----------------------------
A very fast hierachical tree is a nested set or a Celko-tree, it's a bit like a binary tree, or a huffman tree when you have a MySQL storage engine. Disadvantage is expensive deletion and insertion. Other RDBMS supports also recursive queries. In general I didn't see many nested sets. It seems to be complicated too create and maintain. When the nested set is too complicated and the RDBMS doesn't support recursive queries there is also materialized path.
- http://www.ibase.ru/devinfo/DBMSTrees/sqltrees.html
- http://en.wikipedia.org/wiki/Binary_tree
- http://en.wikipedia.org/wiki/Huffman_coding
- http://www.postgresql.org/docs/8.4/static/queries-with.html
- Is it possible to make a recursive SQL query?
- http://www.cybertec.at/pgbook/node122.html
精彩评论