我有一个嵌套的集合模型,如下所示。

HOME
  MUSIC
   GUITAR
   KEY BOARD
   RADIO

  FURNITURE
   BDD
   TABLE

  BOOKS
   BIBLE
   Godfather


我的问题是查询如何在父级中显示子级元素?
例如。

将父级的MUSIC, FURNITURE, BOOKS列为HOME
将父级的GUITAR,KEY BOARD, RADIO列为MUSIC

我尝试了以下查询

select * from elements where lft between 1 and 22 order by lft asc


选择第一个父母的孩子,但返回整个列表。

谁能帮帮我吗 ?

提前致谢

表结构看起来像

-------+-------------------+------------+----------
id     |     cat_name      |   lft      |   rgt
-------|-------------------+------------+----------
1      |       HOME        |   1        |   22

最佳答案

这将给您您想要的:

SELECT
    c.cat_name
FROM
    tree_struc t
JOIN
    tree_struc c
    ON c.lft BETWEEN t.lft + 1 AND t.rgt - 1
LEFT JOIN
    tree_struc a
    ON a.lft BETWEEN t.lft + 1 AND t.rgt - 1
    AND c.lft BETWEEN a.lft + 1 AND a.rgt - 1
WHERE t.cat_name = 'Music' AND a.id IS NULL;


SQL Fiddle

关于mysql - 嵌套集模型查询父级内部的选择节点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26072040/

10-11 10:47