简体   繁体   English

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

[英]MySQL nested set - select node's first N children

Tree example: 树示例:

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

This tree is stored in a MySQL table built on a nested set model (lft, rgt). 该树存储在基于嵌套集模型(lft,rgt)构建的MySQL表中。

How can I select only the first three children (c1,c2,c3) along with all their descendants? 如何仅选择前三个子项(c1,c2,c3)及其所有后代? After that, how can I select only the next two children (c4,c5) along with all their descendants? 之后,我如何只选择接下来的两个孩子(c4,c5)及其所有后代?

You have to locate first entity: 您必须找到第一个实体:

    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';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM