PHP-SQL。从DB中选择类别和多个子类别的非递归方式

时间:2015-06-10 14:07:30

标签: php mysql sql

我试图找到一种方法从父类别中获取每个子类别,在我的情况下,我不知道我将拥有多少个子类别,因此,我找到的唯一解决方案是使用递归。

我用过:

public function recursiveSel(&$tree, $db, $parent = 0){
    $query = $db->query("SELECT id, catName FROM categories WHERE parentCategory=".$parent);

    while($category = $db->fetch_array($query)){
        $tree .= $category['catName'];
        if($category['id'] != $parent){
            $this->treeSelCategories($tree,$db,$category['id']);
        }
    }
}

但我认为,如果有1000个用户正在分类并且我有500个类别,那可能会很乱。

我的类别表构建如下:

|||||||||||||||||||||||||||||
|| id || name    || parent ||
|||||||||||||||||||||||||||||
|| 1  || games   ||  0     ||
|| 2  || courses ||  0     ||
|| 3  || cooking ||  2     ||
|| 4  || diy     ||  2     ||
|| 5  || action  ||  1     ||
|| 6  || new     ||  5     ||
|| 7  || tutorial||  3     ||
|| 8  || easy    ||  7     ||
|||||||||||||||||||||||||||||

结果需要:

games
--action
----new
courses
--cooking
----tutorial
------easy
--diy

有没有办法在不使用递归的情况下执行此操作?可能只有sql? 如果需要,我可以更改数据库结构。

谢谢!

0 个答案:

没有答案
相关问题