這個(gè)方法還是剛哥教我的易阳,當(dāng)時(shí)覺得這才叫寫代碼啊韵卤。
準(zhǔn)備
這里我們假設(shè)有一個(gè)分銷員場景剥啤,分銷員的層級(jí)關(guān)系如上圖衬衬。
我們的表結(jié)構(gòu)如下:
CREATE TABLE mptt
(
`id` int(11) not null auto_increment,
`name` varchar(25) comment '分銷員名稱',
`left` int(11) comment '左值',
`right` int(11) comment '右值',
`level` int(11) comment '層級(jí)',
`amount` int(11) comment '業(yè)績',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
我特意加了業(yè)績字段,用來模擬之后業(yè)績求和的場景狱从。
我們按照上圖的字母順序一個(gè)一個(gè)將數(shù)據(jù)插入膨蛮。
插入
其實(shí)插入節(jié)點(diǎn)就兩種情況叠纹,一個(gè)是插入根節(jié)點(diǎn),一個(gè)是插入子節(jié)點(diǎn)敞葛。我們分別將這兩種情況寫成存儲(chǔ)過程誉察,有興趣的將它翻譯成其他語言就能拿來用了:
# 插入根節(jié)點(diǎn)
DELIMITER //
create procedure add_node
( in name varchar(255), in amount int(11) )
begin
set @left=(select ifnull(max(`right`), 0) from mptt) + 1;
insert into mptt (`name`, `left`, `right`, `level`, `amount`) values(name, @left, @left+1, 1, amount);
end //
# 插入子節(jié)點(diǎn)
DELIMITER //
create procedure add_sub_node
( in name varchar(255), in amount int(11), in parent_id int(11) )
begin
select @parent_left := `left`, @parent_level := `level` from mptt where `id`=parent_id;
update mptt set `left`=`left`+2 where `left`>@parent_left;
update mptt set `right`=`right`+2 where `right`>@parent_left;
insert into mptt (`name`, `left`, `right`, `level`, `amount`) values(name, @parent_left+1, @parent_left+2, @parent_level+1, amount);
end //
我們按照上圖插入節(jié)點(diǎn)
call add_node('A', 6);
call add_sub_node('B', 3, (select id from mptt where name='A'));
call add_sub_node('C', 5, (select id from mptt where name='B'));
call add_sub_node('D', 10, (select id from mptt where name='A'));
call add_sub_node('E', 11, (select id from mptt where name='D'));
call add_sub_node('F', 50, (select id from mptt where name='B'));
此時(shí)表中的數(shù)據(jù)是這樣的:
查詢
當(dāng)我們需要統(tǒng)計(jì)A分銷員所有下級(jí)的業(yè)績之和時(shí),我們只需要輸入一條sql即可查詢出來惹谐,這比用parent_id的方式方便多了持偏。
select @left := `left`, @right := `right` from mptt where name='A';
select sum(amount) from mptt where `left` > @left and `right` < @right
當(dāng)我們只統(tǒng)計(jì)A分銷員直屬下級(jí)的銷售額之和時(shí),level字段起了左右氨肌。
select @left := `left`, @right := `right`, @level := `level` from mptt where name='A';
select sum(amount) from mptt where `left` > @left and `right` < @right and `level` = @level+1
修改
這里的修改是指將E分銷員截出并加入B鸿秆、C分銷員之間,或者將B分銷員以及它下面的整個(gè)子書截出并且放到E分銷員的下面等等怎囚。稍微想一下就能知道實(shí)現(xiàn)起來不是不可能卿叽,只是很復(fù)雜。這個(gè)之后慢慢研究恳守。
總結(jié)
實(shí)際上這個(gè)方法可以支持無限層級(jí)考婴,就算按照規(guī)定分銷員最多只能三級(jí),那也可以用這個(gè)方法來做無限層級(jí)的菜單或者省市區(qū)表什么的催烘。反正總是有地方可以用到的沥阱。