【发布时间】:2014-03-25 11:08:41
【问题描述】:
我有 mysql 表。在该表中,我有两列名为id_category 和id_parent。
id_category | id_parent
1 | 0
2 | 1
3 | 1
4 | 1
5 | 3
6 | 2
7 | 2
8 | 2
9 | 5
10 | 9
11 | 9
12 | 11
13 | 11
id_category 是自动增量,id_parent 具有类别值。在这里,我想获取id_category=13 的根 id_category,它等于id_parent=1。它就像之字形 l.e id_cat =13 所以 id_parent=11, 所以现在 id_cat =11 所以 id_parent=9, id_cat =9 所以 id_parent=5, id_cat =5 所以 id_parent=3, id_cat =3 所以 id_parent=1 现在条件满足。现在我想要父 id = 1 的类别 id .. 在这个查询中预期的答案是 id_category=3。这里对于 id_category=13 id_category=3 是根类别,这正是我想要的。现在我不知道如何编写查询,请帮助我。在此先感谢
【问题讨论】:
-
您的解决方案将非常重要。您的数据模型称为邻接列表。您想阅读一些关于潜在解决方案的文章:stackoverflow.com/questions/10999888/… 和 mikehillyer.com/articles/managing-hierarchical-data-in-mysql
-
非常感谢您的回复
-
但在 mike 文章中,他没有说明如何按顺序获取列表,例如:[10]2 WAY RADIOS ->[6]PORTABLE ELECTRONICS->[1]ELECTRONICS。如果我将类别 ID 指定为 [10],那么我想要根类别([1] 电子产品)。这篇文章有点用但不完全:(请推荐一些其他文章