MySQL嵌套集 - 选择节点的前N个子节点

时间:2013-09-13 09:44:04

标签: mysql hierarchical-data nested-sets

树例子:

ROOT
 -c1
  -g11
 -c2
 -c3
   -g31
   -g32
 -c4
 -c5
  -g51

此树存储在基于嵌套集模型(lft,rgt)构建的MySQL表中。

如何只选择前三个孩子(c1,c2,c3)及其所有后代? 之后,我怎样才能选择接下来的两个孩子(c4,c5)及其所有后代?

1 个答案:

答案 0 :(得分:0)

您必须找到第一个实体:

    SELECT 
t1.name AS lev1, IF(t1.name=@sth,'',@sth := t1.name ) lev1_1, 
t2.name AS lev2 , IF(t2.name=@sth2,'',@sth2 := t2.name ) lev2_2, 
t3.name AS lev3 , IF(t3.name=@sth3,'',@sth3 := t3.name ) lev3_3,
t4.name AS lev4 , IF(t4.name=@sth4,'',@sth4 := t4.name ) lev4_4
    FROM    
(SELECT @sth:=NULL, @sth2:=NULL, @sth3:=NULL, @sth4:=NULL) AS del,  
category AS t1
LEFT JOIN category AS t2 ON t2.parent = t1.category_id
LEFT JOIN category AS t3 ON t3.parent = t2.category_id
LEFT JOIN category AS t4 ON t4.parent = t3.category_id
    WHERE 
t1.name = 'ELECTRONICS';