MySQL嵌套层次结构选择

时间:2014-10-13 07:56:06

标签: mysql nested hierarchy

我在MySQL中有一个下一个嵌套层次结构:

ROOT
|
+--Group1
|
+--Group2
|   |
|   +--SubGroup1
|   |
|   +--ABC
|
+--Group3
|  |
|  +--SubGroup2
|
+--Group4
|  |
|  +--SubGroup1
|     |
|     +--ABC

表格内容为:

mysql> select * from nest;
+----+------+------------+------+
| id | lft  | group_name | rgt  |
+----+------+------------+------+
|  1 |    1 | ROOT       |   20 |
|  2 |    2 | Group1     |    3 |
|  3 |    4 | Group2     |    9 |
|  4 |    5 | SubGroup1  |    8 |
|  5 |    6 | ABC        |    7 |
|  6 |   10 | Group3     |   13 |
|  7 |   11 | SubGroup2  |   12 |
|  8 |   14 | Group4     |   19 |
|  9 |   15 | SubGroup1  |   18 |
| 10 |   16 | ABC        |   17 |
+----+------+------------+------+

我正在尝试从MySQL的嵌套层次结构中选择所有树。

SELECT
    CONCAT( REPEAT(' ', COUNT(parent.group_name) - 1), node.group_name) AS group_name
FROM 
    nest AS node,
    nest AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY
    node.group_name
ORDER BY
    node.lft;

获得结果,重复的孩子只有第一场比赛:

+----------------+
| group_name     |
+----------------+
| ROOT           |
|  Group1        |
|  Group2        |
|      SubGroup1 |
|        ABC     |
|  Group3        |
|   SubGroup2    |
|  Group4        |
+----------------+

我如何获得Group4的重复结果,类似Group2? 像这样:

+----------------+
| group_name     |
+----------------+
| ROOT           |
|  Group1        |
|  Group2        |
|      SubGroup1 |
|        ABC     |
|  Group3        |
|   SubGroup2    |
|  Group4        |
|      SubGroup1 |
|        ABC     |
+----------------+

谢谢。

1 个答案:

答案 0 :(得分:1)

更改

GROUP BY
node.group_name

GROUP BY
node.id

喜欢这个

SELECT
    CONCAT( REPEAT(' ', COUNT(parent.group_name) - 1), node.group_name) AS group_name
FROM 
    nest AS node,
    nest AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY
    node.id
ORDER BY
    node.lft