层次结构的数据库处理
2010-03-12 00:00:00 来源:WEB开发网SELECT node.name, (COUNT(parent.name) - (sub_tree.depth + 1)) AS depth
FROM nested_category AS node,
nested_category AS parent,
nested_category AS sub_parent,
(
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
AND node.name = 'PORTABLE ELECTRONICS'
GROUP BY node.name
ORDER BY node.lft
)AS sub_tree
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt
AND sub_parent.name = sub_tree.name
GROUP BY node.name
ORDER BY node.lft;
+----------------------+-------+
| name | depth |
+----------------------+-------+
| PORTABLE ELECTRONICS | 0 |
| MP3 PLAYERS | 1 |
| FLASH | 2 |
| CD PLAYERS | 1 |
| 2 WAY RADIOS | 1 |
+----------------------+-------+
这个方法中可以使用任何节点的name,包括根节点。深度值总能根据 name 获取到。
查找直接的下级节点
假设我们想在一个零售商的网站上显示电子产品的分类。当一个用户点击一个类别时,你想给他显示该类别下的产品,并且显示其直接的子类别,而不是该类下所有的子树,不需要搜索所有的子孙。例如,当点击 PORTABLE ELECTRONICS 时, 我们想展示 MP3 PLAYERS, CD PLAYERS, 和 2 WAY RADIOS,但是不包括 FLASH.
更多精彩
赞助商链接