一级嵌套在Mysql中

时间:2012-10-06 07:47:07

标签: mysql

我有桌子

+-------------+----------------------+--------------------+
| 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 个答案:

答案 0 :(得分: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上查看。