如以下树状结构:
├── 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 | "-" | 1 |
| 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 |
-
id:本节点的primary key
-
parent_id:其值为父节点的primary key
-
key:可以称为线索,从跟节点到父节点的primary key,中间用任意非数字符号分割
-
level:表示当前节点到根节点的距离
于是,在给定一个节点d的时候:
- 查找level=1的d的所有子孙节点
select * from table_name where key like "${d.id}-%"
- 查找level>=2的d的所有子孙节点
select * from table_name where key like "${d.key}${d.id}-%"
- 查找子节点
select * from table_name where key like "${d.key}${d.id}-%" and level=${d.level}+1