如何以递归方式获取此MySQL表中行的“父ID”?

时间:2010-10-24 02:52:56

标签: php mysql recursion

我的数据库看起来像(pligg cms,示例数据)

id  catID parentID   catName
1    1      0        location
2    2      0        color
3    3      1        USA
4    4      3        Illinois
5    5      3        Chicago
6    6      2        Black
7    7      2        Red

假设我如何获得芝加哥的顶级parentID,它应该是位置。

我是否在php中编写了递归函数,或者这在mysql中是否可行?

3 个答案:

答案 0 :(得分:6)

This网站非常清楚地概述了在mysql和PHP中存储分层数据的不同方法。要回答你的问题,最简单的方法是使用php和递归。您可以使用其他方法,例如modified preorder transversal,它们不需要多个数据库查询。但是,在处理大量插入和更新时,这种方法可能会更复杂。

另一个非常酷的方法和我个人最喜欢的是What is the most efficient/elegant way to parse a flat table into a tree?中提到的所谓的“闭包表”/“邻接​​关系”

关于你的评论,你基本上必须做一个循环或一个递归函数,选择芝加哥的父母,然后是父母的父母,等等。

$stack = array();
$parent = 3;
while($parent != 0){
    $data = (put your mysql to get the row with parentID = $parent)
    $parent = data['parentID'];
    $stack[] = $data;
}

$stack = array_reverse($stack);
然后,堆栈将包含芝加哥的父母(即位置,美国)

答案 1 :(得分:0)

由于mysql还没有支持诸如connect by(oracle)或公用表表达式(sql server)之类的功能,所以你遇到的大多数例子都需要从php到mysql的多次调用 - 在层次结构中每个级别调用一次。如果您拥有许多级别的树和许多并发用户,这很快就会增加例如深度为20的树,其中1000个用户需要对数据库进行20K调用。以下方法使用存储过程,对于相同的方案,只需要1000次调用(每个用户1次)。你对结果集的处理取决于你:你可能会生成一个XML DOM,将它加载到一个数组中或者只是将它输出为HTML,重要的是你在一次调用中将整个树放在结果集中。

编辑:添加了一个最初误读了您的问题的category_parent存储过程。

示例mysql调用

call category_hier(1);
call category_hier(2);

call category_parent(5);
call category_parent(7);

示例php脚本

<?php

$conn = new mysqli("localhost", "foo_dbo", "pass", "foo_db", 3306);

$result = $conn->query(sprintf("call category_parent(%d)", 5));
$row = $result->fetch_assoc();
$result->close();
$conn->close();

echo sprintf("parent category is : cat_id = %s category_name = %s",
 $row["cat_id"], $row["category_name"]);

?>

<?php

$conn = new mysqli("localhost", "foo_dbo", "pass", "foo_db", 3306);

$result = $conn->query(sprintf("call category_hier(%d)", 1));

echo "<table border='1'>
        <tr><th>cat_id</th><th>category_name</th><th>parent_cat_id</th>
        <th>parent_category_name</th><th>depth</th></tr>";

while($row = $result->fetch_assoc()){
    echo sprintf("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", 
        $row["cat_id"],$row["category_name"],$row["parent_cat_id"],
        $row["parent_category_name"],$row["depth"]);
}

echo "</table>";

$result->close();
$conn->close();

?>

可在此处找到完整脚本 - http://pastie.org/1244582 或参见下文:

-- TABLES

drop table if exists categories;
create table categories
(
cat_id smallint unsigned not null auto_increment primary key,
name varchar(255) not null,
parent_cat_id smallint unsigned null,
key (parent_cat_id)
)
engine = innodb;

-- TEST DATA

insert into categories (name, parent_cat_id) values
('Location',null), 
('Color',null), 
   ('USA',1), 
      ('Illinois',3), 
      ('Chicago',3), 
   ('Black',2), 
   ('Red',2);


-- STORED PROCEDURES

drop procedure if exists category_parent;

delimiter #

create procedure category_parent
(
in p_cat_id smallint unsigned
)
begin

declare v_done tinyint unsigned default 0;
declare v_depth smallint unsigned default 0;

create temporary table hier(
 parent_cat_id smallint unsigned, 
 cat_id smallint unsigned, 
 depth smallint unsigned default 0
)engine = memory;

insert into hier select parent_cat_id, cat_id, v_depth from categories where cat_id = p_cat_id;

/* http://dev.mysql.com/doc/refman/5.0/en/temporary-table-problems.html */

create temporary table tmp engine=memory select * from hier;

while not v_done do

    if exists( select 1 from categories p inner join hier on p.cat_id = hier.parent_cat_id and hier.depth = v_depth) then

        insert into hier 
            select p.parent_cat_id, p.cat_id, v_depth + 1 from categories p 
            inner join tmp on p.cat_id = tmp.parent_cat_id and tmp.depth = v_depth;

        set v_depth = v_depth + 1;          

        truncate table tmp;
        insert into tmp select * from hier where depth = v_depth;

    else
        set v_done = 1;
    end if;

end while;

select 
 c.cat_id,
 c.name as category_name
from 
 hier
inner join categories c on hier.cat_id = c.cat_id
where
 hier.parent_cat_id is null;


drop temporary table if exists hier;
drop temporary table if exists tmp;

end #

delimiter ;


drop procedure if exists category_hier;

delimiter #

create procedure category_hier
(
in p_cat_id smallint unsigned
)
begin

declare v_done tinyint unsigned default 0;
declare v_depth smallint unsigned default 0;

create temporary table hier(
 parent_cat_id smallint unsigned, 
 cat_id smallint unsigned, 
 depth smallint unsigned default 0
)engine = memory;

insert into hier select parent_cat_id, cat_id, v_depth from categories where cat_id = p_cat_id;

/* http://dev.mysql.com/doc/refman/5.0/en/temporary-table-problems.html */

create temporary table tmp engine=memory select * from hier;

while not v_done do

    if exists( select 1 from categories p inner join hier on p.parent_cat_id = hier.cat_id and hier.depth = v_depth) then

        insert into hier 
            select p.parent_cat_id, p.cat_id, v_depth + 1 from categories p 
            inner join tmp on p.parent_cat_id = tmp.cat_id and tmp.depth = v_depth;

        set v_depth = v_depth + 1;          

        truncate table tmp;
        insert into tmp select * from hier where depth = v_depth;

    else
        set v_done = 1;
    end if;

end while;

select 
 p.cat_id,
 p.name as category_name,
 b.cat_id as parent_cat_id,
 b.name as parent_category_name,
 hier.depth
from 
 hier
inner join categories p on hier.cat_id = p.cat_id
left outer join categories b on hier.parent_cat_id = b.cat_id
order by
 hier.depth, hier.cat_id;

drop temporary table if exists hier;
drop temporary table if exists tmp;

end #

delimiter ;

-- TESTING (call this stored procedure from php)

call category_hier(1);

call category_hier(2);

call category_parent(5);

call category_parent(7);

希望这有帮助。

答案 2 :(得分:0)

基于@GWW回答

function getLocationArray($start){
    $link=dbConnect();//a function returning the link with your db
    $stack = array();
    $parent = $start;
    while($parent != 0){
        $query='SELECT catName,parentID from myTable where catId='.$parent;
        $result = mysql_query($query,$link);
        while($row = mysql_fetch_assoc($result)){
            $parent=$row['parentID'];
            $name=$row['catName'];
            $stack[] = $name;
            /*foreach($row as $cname => $cvalue){
            }*/
        }
    }
    $stack = array_reverse($stack);
    return $stack;
}
var_dump($stack);