1

我必须管理我不是 SQL 专家,也许这个查询真的很简单,但我无法编写它。基本上所有页面都是使用邻接列表模型排列的(我也在跟踪深度):

+----+---------------+-------------------+-----------+
| id | title         | level | position  | parent_id |
+----+---------------+-------+-----------+-----------+
|  1 | Home          | 0     | 0         | null      |
+----+---------------+-------+-----------+-----------+
|  2 | Resources     | 0     | 1         | null      |
+----+---------------+-------+-----------+-----------+
|  3 | About         | 0     | 2         | null      |
+----+---------------+-------+-----------+-----------+
|  4 | Documents     | 1     | 0         | 2         |
+----+---------------+-------+-----------+-----------+
|  5 | Tutorials     | 1     | 1         | 2         |
+----+---------------+-------+-----------+-----------+

请注意,位置在同一个父级中是唯一的。

我想要实现的是按 parent 和 position 排序,但父类别应该列在它的孩子之前。这很明显并且不起作用:

SELECT * FROM PAGE p
ORDER BY parent_id, position

结果是第一个表。我需要的是以下内容:

+----+---------------+-------------------+-----------+
| id | title         | level | position  | parent_id |
+----+---------------+-------+-----------+-----------+
|  1 | Home          | 0     | 0         | null      |
+----+---------------+-------+-----------+-----------+
|  2 | Resources     | 0     | 1         | null      | // Parent of 4, 5
+----+---------------+-------+-----------+-----------+
|  4 | Documents     | 1     | 0         | 2         | // Child of Resource
+----+---------------+-------+-----------+-----------+
|  5 | Tutorials     | 1     | 1         | 2         | // Child of Resource
+----+---------------+-------+-----------+-----------+
|  3 | About         | 0     | 2         | null      |
+----+---------------+-------+-----------+-----------+

这在 MySQL 中是否可能,不支持递归?

4

1 回答 1

0

当您可以限制查询时,您可以使用自联接。或者尝试嵌套集或 celko-tree。

于 2013-11-09T22:05:35.373 回答