我正在学习嵌套集及其在生成分层列表中的用法。在其他资源中,我特别指的是http://www.artfulsoftware.com/mysqlbook/sampler/mysqled1ch20.html和http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/。有人可以告诉我我做错了什么,因为当我查询数据时项目的深度不正确吗?
这是我的例子的图形表示:
[哦,不,不是!一旦我的代表级别允许,我会尝试为将来的用户编辑它。]
我在MySQL中创建了一个表,并按如下方式插入数据:
CREATE TABLE page_temp (
page_id INTEGER unsigned NOT NULL AUTO_INCREMENT,
page_name VARCHAR(255) NOT NULL,
lft INT NOT NULL,
rgt INT NOT NULL,
PRIMARY KEY (page_id)
);
INSERT INTO page_temp VALUES
(28, 'g', 52, 53),
(27, 'f', 50, 51),
(26, 'e', 40, 41),
(25, 'd', 38, 39),
(24, 'c', 10, 11),
(23, 'b', 8, 9),
(22, 'a', 6, 7),
(21, 10, 49, 54),
(20, 9, 47, 48),
(19, 8, 43, 44),
(18, 7, 37, 42),
(17, 6, 29, 30),
(16, 5, 21, 22),
(15, 4, 19, 20),
(14, 3, 17, 18),
(13, 2, 5, 12),
(12, 1, 3, 4),
(11, 'H', 46, 55),
(10, 'G', 36, 45),
(9, 'F', 32, 33),
(8, 'E', 28, 31),
(7, 'D', 26, 27),
(6, 'C', 16, 23),
(5, 'B', 14, 45),
(4, 'A', 2, 13),
(3, 'III', 35, 56),
(2, 'II', 25, 34),
(1, 'I', 1, 24)
;
然后我用这个查询拉出集合:
SELECT CAST(node.page_name AS BINARY) AS title, node.lft, node.rgt, (COUNT(parent.page_name) - 1) AS depth
-> FROM page_temp AS node CROSS JOIN page_temp AS parent
-> WHERE node.lft BETWEEN parent.lft AND parent.rgt
-> GROUP BY title
-> ORDER BY node.lft;
+-------+-----+-----+-------+
| title | lft | rgt | depth |
+-------+-----+-----+-------+
| I | 1 | 24 | 0 |
| A | 2 | 13 | 1 |
| 1 | 3 | 4 | 2 |
| 2 | 5 | 12 | 2 |
| a | 6 | 7 | 3 |
| b | 8 | 9 | 3 |
| c | 10 | 11 | 3 |
| B | 14 | 45 | 1 |
| C | 16 | 23 | 2 |
| 3 | 17 | 18 | 3 |
| 4 | 19 | 20 | 3 |
| 5 | 21 | 22 | 3 |
| II | 25 | 34 | 1 |
| D | 26 | 27 | 2 |
| E | 28 | 31 | 2 |
| 6 | 29 | 30 | 3 |
| F | 32 | 33 | 2 |
| III | 35 | 56 | 1 |
| G | 36 | 45 | 2 |
| 7 | 37 | 42 | 3 |
| d | 38 | 39 | 4 |
| e | 40 | 41 | 4 |
| 8 | 43 | 44 | 3 |
| H | 46 | 55 | 1 |
| 9 | 47 | 48 | 2 |
| 10 | 49 | 54 | 2 |
| f | 50 | 51 | 3 |
| g | 52 | 53 | 3 |
+-------+-----+-----+-------+
28 rows in set (0.00 sec)
在这种情况下,我使用CAST来强制执行唯一值。我已经通过许多不同的方式调整了查询,但我无法理解如何获得正确的输出。顺序是应该的,但深度从项目“C”开始偏离轨道,然后在项目“H”处重新调整。我希望实现的结果是(对深度列进行了更改):
+-------+-----+-----+-------+
| title | lft | rgt | depth |
+-------+-----+-----+-------+
| I | 1 | 24 | 0 |
| A | 2 | 13 | 1 |
| 1 | 3 | 4 | 2 |
| 2 | 5 | 12 | 2 |
| a | 6 | 7 | 3 |
| b | 8 | 9 | 3 |
| c | 10 | 11 | 3 |
| B | 14 | 45 | 1 |
| C | 16 | 23 | 1 |
| 3 | 17 | 18 | 2 |
| 4 | 19 | 20 | 2 |
| 5 | 21 | 22 | 2 |
| II | 25 | 34 | 0 |
| D | 26 | 27 | 1 |
| E | 28 | 31 | 1 |
| 6 | 29 | 30 | 2 |
| F | 32 | 33 | 1 |
| III | 35 | 56 | 0 |
| G | 36 | 45 | 1 |
| 7 | 37 | 42 | 2 |
| d | 38 | 39 | 3 |
| e | 40 | 41 | 3 |
| 8 | 43 | 44 | 2 |
| H | 46 | 55 | 1 |
| 9 | 47 | 48 | 2 |
| 10 | 49 | 54 | 2 |
| f | 50 | 51 | 3 |
| g | 52 | 53 | 3 |
+-------+-----+-----+-------+
一旦运行正常,我将使用Generate Nested UL's Based Upon Variable Depth Data中的注释重建输出。谢谢你的眼睛和帮助!
答案 0 :(得分:0)
我盯着手绘的嵌套图表两天。我甚至为世界做了一个很好的图形[希望]帮助我解决我的问题。我甚至将我的明显错误复制到图像文件中。
项目'B'应该是{14,15},而不是{14,45}。这就是为什么巢在项目'H'{46,55}恢复正常。我的妻子总是说我的笔迹不好,我给你留下了一个怯懦的帖子......