php - 如果表有嵌套记录,我如何从 mysql 表中获取主要值

标签 php mysql

我有如下表格,

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

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

最佳答案

我认为您应该从 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']);
    }
}

关于php - 如果表有嵌套记录,我如何从 mysql 表中获取主要值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40859534/

相关文章:

php - Google Analytics API 获取具有维度的数据

php - 如何获取多个查询的连接数?

mysql - 查找 mysql 列中的相似性

mysql - 根据条件按顺序向 MySQL 单元格的日期/时间字段添加一秒

php - Symfony2 路由 : Two optional parameters - at least one required

php - CodeIgniter Controller 中的PHP新行

MySQL:连接查找不匹配的字段

javascript - 如何在不刷新的情况下编辑和删除MySQL数据库的记录?

php - MySQL - 主键的重复条目(但实际上不是......)

Php:$var 和 &$var 有什么区别?