【问题标题】:how can i get the main value from mysql table, if the table has nested records如果表有嵌套记录,我如何从 mysql 表中获取主值
【发布时间】: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

那么,是否有任何简单的方法可以在不递归运行查询的情况下更轻松地获得结果?

【问题讨论】:

标签: php mysql


【解决方案1】:

我认为您应该从 db 中获取所有类别,然后在 php 中选择当前类别。 示例

$categories = mysql_fetch_array(mysql_query('select id,parent from category'));
foreach($categories as $cat){
    $this->categories[$cat['id']][] = $cat;
}

选择类别:

public function getParentCategory($catId)
{
    if ($this->categories[$catId]['parent']  == 0) {
        return $this->categories[$catId]['id'];
    } else {
        return $this->getParentCategory($this->categories[$catId]['parent']);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 2021-08-15
    相关资源
    最近更新 更多