树示例:
ROOT
-c1
-g11
-c2
-c3
-g31
-g32
-c4
-c5
-g51
该树存储在基于嵌套集模型(lft、rgt)构建的 MySQL 表中。
我怎样才能只选择前三个 child (c1,c2,c3)及其所有后代? 之后,我如何才能只选择接下来的两个 child (c4,c5)及其所有后代?
最佳答案
您必须找到第一个实体:
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';
关于MySQL嵌套集-选择节点的前N个子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18783138/