嵌套集二叉树,查询最左边和最右边的节点

时间:2018-09-22 19:29:41

标签: mysql sql database binary-tree nested-sets

我有一个MySQL表,在具有一些额外属性的嵌套集合模型中存储了一个二叉树。二叉树既不完整也不完整,因此中间可能只有一个孩子。

看起来像这样(但有更多数据):

+----+------+-------+-----------+-------+----------+--------------------+
| id | left | right | parent_id | level | position | number_of_children |
+----+------+-------+-----------+-------+----------+--------------------+
|  1 |    1 |     8 | NULL      |     1 | LEFT     |                  3 |
|  2 |    2 |     3 | 1         |     2 | LEFT     |                  0 |
|  3 |    4 |     7 | 1         |     2 | RIGHT    |                  1 |
|  4 |    5 |     6 | 2         |     3 | LEFT     |                  0 |
+----+------+-------+-----------+-------+----------+--------------------+

如何查询树或子树的最左最右节点?

一些图形说明:https://imgur.com/w7gxtOC

我尝试了多种方法,但是这些方法不适用于所有情况(这些是最左边的示例):

SELECT * FROM nodes
  WHERE position = 'LEFT' 
    AND number_of_children < 2
  HAVING `right` = `left` + 1
  ORDER BY element.`left` ASC
  LIMIT 1;

或者这一个,它肯定找到了解决方案,但也找到了一些错误的解决方案:

SELECT * FROM nodes AS element
  JOIN nodes AS upline ON element.parent_id = upline.id
  WHERE upline.position = 'LEFT'
    AND element.position = 'LEFT'
    AND element.number_of_children < 2
  ORDER BY element.`left` ASC;

0 个答案:

没有答案