1 select child.id,child.name,child.lft,child.rgt,count(child.name) depth2 from category parent, category child 3 where child.left >= parent.left
4 and child.right <= parent.right
5 group by child.name 6 order by child.left;
樹狀節點的特點:
1. 每一個節點都有一個左右值。
2. 如果右值-左值=1,則代表當前節點為葉子節點。
3. 如果右值-左值>1,則代表當前節點有孩子節點,值在左右值之間的所有節點,即為當前結點的所有孩子節點。
數據庫表設計:
create table category
(
id varchar(40) primary key,
name varchar(100),
lft int,
rgt int
);
insert into category values('1','商品',1,18);
insert into category values('2','平板電視',2,7);
insert into category values('3','冰箱',8,11);
insert into category values('4','筆記本',12,17);
insert into category values('5','長虹',3,4);
insert into category values('6','索尼',5,6);
insert into category values('7','西門子',9,10);
insert into category values('8','thinkpad',13,14);
insert into category values('9','dell',15,16);
問題:為了在頁面中顯示樹狀結構,需要得到所有結點,以及每個結點在樹中的層次:
解決思路:
1、 要得到結點的層次,就是看節點有幾個父親,例如長虹有2個父親,則它所在層次就為2。
2、 如何知道每一個節點有幾個父親呢?這個表有個特點,父親和孩子都在同一個表中,為得到父親所有的孩子,可以把這張表想像成兩張表,一張用於保存父親,一張表保存孩子,如下所示:
select * from category parent,category child;
3、 父親下面的孩子有個特點,它的左值>父親的左值,並且<父親的右值,如下所示
select * from category parent,category child where child.lft>=parent.lft and child.rgt<=parent.rgt;
以上語句會得到父親下面所有的孩子。
4、 對父親所有孩子的姓名進行歸組,然后使用count統計函數,這時就會知道合並了幾個孩子,合並了幾個孩子姓名,這個孩子就有幾個父親,從而知道它所在的層次
select child.name,count(child.name) depth from category parent,category child where child.lft>=parent.lft and child.rgt<=parent.rgt group by child.name;
5、 最后根據左值排序即可
select child.name,count(child.name) depth from category parent,category child where child.lft>=parent.lft and child.rgt<=parent.rgt group by child.name order by child.lft;