【发布时间】:2016-11-29 06:54:43
【问题描述】:
我有一张如下表,
id | name |parent
---| --- | ---
1 |vehicle|0
2 |car |1
3 |test |0
4 |maruti |2
5 |alto |4
6 |test2 |3
我的类别 ID 为 5。现在我想要 id 为 5 的第一个父类别。
id 5 的第一个父类别是 1(车辆)
为此,我需要运行 4 个查询才能得到它。
例如,
public function getParentCategory($catId)
{
$cat = mysql_fetch_array(mysql_query('select id,parent from category where id=$catId'));
if ($cat['parent'] == 0) {
return $cat['id'];
} else {
return $this->getParentCategory($cat['id']);
}
}
现在上面的函数运行 3 次来获取类别 alto 的第一个父级的 id
那么,是否有任何简单的方法可以在不递归运行查询的情况下更轻松地获得结果?
【问题讨论】:
-
我不明白你到底想要什么?如果你有 id 我猜那是主键而不是什么问题?
-
你能告诉我们你的架构吗