設計樹形結構,後面再研究下是否可行數據結構
若是你的樹深度是可預期的話,有個超簡單的數據結構。你須要3個字段來表達這個樹:spa
其中,key字段的值爲:從跟節點到父節點的primary key,中間用任意非數字符號分割。設計
例如如下樹狀結構code
├── a │ ├── d │ │ ├── p │ │ ├── q │ │ └── r │ ├── e │ └── f ├── b │ ├── x │ ├── y │ └── z ├── c
| id | value | parent_id | key | level |
| 1 | a | 0 | "-" | 1 | | 2 | b | 0 | "-" | 1 | | 3 | c | 0 | "-" | 2 | | 4 | d | 1 | "1-" | 2 | | 5 | e | 1 | "1-" | 2 | | 6 | f | 1 | "1-" | 2 | | 7 | x | 2 | "2-" | 2 | | 8 | y | 2 | "2-" | 2 | | 9 | z | 2 | "2-" | 2 | | 10 | p | 4 | "1-4-" | 3 | | 11 | q | 4 | "1-4-" | 3 | | 12 | r | 4 | "1-4-" | 3 |
因而,在給定一個節點d的時候,string
select * from table_name where key like "${d.id}-${d.key}-%"
select * from table_name where key like "${d.id}-${d.key}-%" and level=${d.level}+1