0

我有桌子

+-------------+----------------------+--------------------+
| category_id | name                 | parent_category_id |
+-------------+----------------------+--------------------+
|           1 | Pizzas               |               NULL |
|           2 | Cheese Pizzas        |                  1 |
|           3 | Spicy Pizzas         |                  1 |
|           4 | Shakes               |               NULL |
|           5 | Milk Shakes          |                  4 |

我只有单层嵌套,它会是一样的

我希望检索像

Pizza
   Cheese Pizzas
   Spicy Pizzas
Shakes
   Milk Shakes

在 MySQL 中是否有像 Oracle 中的“树”之类的东西,我确实阅读了文章http://ftp.nchu.edu.tw/MySQL/tech-resources/articles/hierarchical-data.html

当存在动态嵌套级别时,更改表结构似乎更可行,就我而言,它始终为 1

有什么建议么?

4

1 回答 1

3

您可以使用自联接并执行以下操作:

SELECT   parent.category_id, parent.name AS parent, child.name AS child
FROM     my_table parent JOIN my_table child
      ON parent.parent_category_id IS NULL
     AND child.parent_category_id = parent.category_id
ORDER BY parent.category_id, child.category_id

sqlfiddle上查看。

如果需要,甚至可以对结果进行分组:

SELECT   parent.name, GROUP_CONCAT(child.name ORDER BY child.category_id)
FROM     my_table parent JOIN my_table child
      ON parent.parent_category_id IS NULL
     AND child.parent_category_id = parent.category_id
GROUP BY parent.category_id
ORDER BY parent.category_id

sqlfiddle上查看。

于 2012-10-06T07:52:29.580 回答