本文参考了: Mike Hillyer的《Managing Hierarchical Data in MySQL》 及Yimin的翻译版《MYSQL中分层数据的管理》
#3.检索单一路径
在嵌套集合模型中,我们可以不用多个自连接就可以检索出单一路径:
1 2 3 4 5 6
SELECT parent.name FROM nested_category node, nested_category parent WHERE node.lft BETWEEN parent.lft AND parent.rgt AND node.name ='FLASH' ORDERBY parent.lft;
输出结果
1 2 3 4 5 6
NAME -------------------- ELECTRONICS PORTABLE ELECTRONICS MP3 PLAYERS FLASH
SELECT node.name, (COUNT(parent.name) -1) AS depth FROM nested_category node, nested_category parent WHERE node.lft BETWEEN parent.lft AND parent.rgt GROUPBY node.name
SELECT node.name, (COUNT(parent.name) -(sub_tree.depth +1)) depth FROM nested_category node, nested_category parent, nested_category sub_parent, ( SELECT node.name, (COUNT(parent.name) -1) AS depth FROM nested_category node, nested_category parent WHERE node.lft BETWEEN parent.lft AND parent.rgt AND node.name ='PORTABLE ELECTRONICS' GROUPBY node.name ) 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 GROUPBY node.name,node.lft,sub_tree.depth ORDERBY node.lft;