层次结构的数据库处理
2010-03-12 00:00:00 来源:WEB开发网查询节点的深度
我们已经可以显示整棵树了,如果我们想获得节点的深度以便更好地识别其在层次结构中的位置,该如何做呢?这可以通过添加一个 COUNT 函数和 GROUP BY 子句实现:
SELECT node.name, (COUNT(parent.name) - 1) AS depth
FROM nested_category AS node,
nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY node.name
ORDER BY node.lft;
+---------------------------+-------+
| name | depth |
+---------------------------+-------+
| ELECTRONICS | 0 |
| TELEVISIONS | 1 |
| TUBE | 2 |
| LCD | 2 |
| PLASMA | 2 |
| PORTABLE ELECTRONICS | 1 |
| MP3 PLAYERS | 2 |
| FLASH | 3 |
| CD PLAYERS | 2 |
| 2 WAY RADIOS | 2 |
+---------------------------+-------+
更多精彩
赞助商链接