一尘不染

MySQL嵌套集-如何查找节点的父级?

mysql

我使用以下各列来运行磨机嵌套集层次结构类型设置:

表名:

myset

列:

id, name, lft, rgt

有谁知道查询以确定节点的 父级

我读了几个地方,在表中也有一个 parent_id
列来跟踪它很方便,但是它看起来很多余,而且如果添加/时查询执行不正确,它似乎可能与嵌套集不同步删除/移动集合中的任何内容。


阅读 311

收藏
2020-05-17

共1个答案

一尘不染

这个问题。它与您的相似。我在那里发布了您可能需要的查询。

SELECT title, (SELECT TOP 1 title 
           FROM tree t2 
           WHERE t2.lft < t1.lft AND t2.rgt > t1.rgt    
           ORDER BY t2.rgt-t1.rgt ASC) AS parent
FROM tree t1
ORDER BY rgt-lft DESC

希望您有需要。

对于下表:

+-------------+----------------------+-----+-----+
| category_id | name                 | lft | rgt |
+-------------+----------------------+-----+-----+
|           1 | ELECTRONICS          |   1 |  20 |
|           2 | TELEVISIONS          |   2 |   9 |
|           3 | TUBE                 |   3 |   4 |
|           4 | LCD                  |   5 |   6 |
|           5 | PLASMA               |   7 |   8 |
|           6 | PORTABLE ELECTRONICS |  10 |  19 |
|           7 | MP3 PLAYERS          |  11 |  14 |
|           8 | FLASH                |  12 |  13 |
|           9 | CD PLAYERS           |  15 |  16 |
|          10 | 2 WAY RADIOS         |  17 |  18 |

它产生输出:

title                | parent
----------------------------------------------
ELECTRONICS          | NULL
PORTABLE ELECTRONICS | ELECTRONICS
TELEVISIONS          | ELECTRONICS
MP3 PLAYERS          | PORTABLE ELECTRONICS
FLASH                | MP3 PLAYERS
CD PLAYERS           | PORTABLE ELECTRONICS
2 WAY RADIOS         | PORTABLE ELECTRONICS
TUBE                 | TELEVISIONS
LCD                  | TELEVISIONS
PLASMA               | TELEVISIONS
2020-05-17