0

嘿,我已经使用以下方法在 mysql 表中实现了一棵树:

http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

这是您拥有如下表格的方法:

+-------------+----------------------+-----+-----+
| 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 |
+-------------+----------------------+-----+-----+

要像平常一样打印表格,您只需按 lft 列排序。是否有任何简单的方法可以反向排序,或者有另一个像“成本”这样的列,其中相同“深度”的所有条目都按成本排序?

谢谢

4

1 回答 1

0

您引用的 URL 显示了如何获得一个SELECT提供深度的 - 如果您将其嵌套到另一个SELECT中,您可以根据需要订购。例如:

SELECT thename, thedepth
FROM (
  SELECT node.name AS thename, (COUNT(parent.name) - 1) AS thedepth
  FROM nested_category AS node,
  nested_category AS parent
  WHERE node.lft BETWEEN parent.lft AND parent.rgt
  GROUP BY node.name
  ORDER BY node.lft) plain
ORDER BY thedepth DESC;

同样,当然,您可以node.cost AS thecost在 inner 中拥有 a as well ,SELECT在 outer 中获得它,SELECT等等ORDER BY thedepth DESC, thecost ASC

性能可能不错,也可能不不错,但您只能通过尝试(EXPLAIN SELECT并添加适当的索引;-)来判断。

如果您有一个足够智能的数据库引擎,则不需要嵌套——您可以直接ORDER BY计算列(如此thedepth处所示)。但我认为这个解决方案适用于更多/更旧的数据库引擎/版本。

于 2009-06-15T00:09:54.443 回答