【发布时间】:2012-07-21 01:34:45
【问题描述】:
嗨,我正在使用 codeigniter 和 MySQL 我有一个这样的表结构。
当我传递父标题时,我得到了所有子值。
这是代码
<?php <br>
// $parent is the parent of the children we want to see <br>
// $level is increased when we go deeper into the tree, <br>
// used to display a nice indented tree <br>
function display_children($parent, $level) { <br>
// retrieve all children of $parent <br>
$result = mysql_query('SELECT title FROM tree '. <br>
'WHERE parent="'.$parent.'";'); <br>
<br>
// display each child <br>
while ($row = mysql_fetch_array($result)) { <br>
// indent and display the title of this child <br>
echo str_repeat(' ',$level).$row['title']."\n"; <br>
<br>
// call this function again to display this <br>
// child's children <br>
display_children($row['title'], $level+1); <br>
} <br>
} <br>
?>
当我通过display_children('',0); 我得到
Food<br>
Fruit<br>
Red<br>
Cherry<br>
Yellow<br>
Banana<br>
Meat<br>
Beef<br>
Pork
要显示“水果”子树,您可以运行 display_children('Fruit',0);
- 如您所见,这是一个递归函数。当子层级增长时,效率低下,查询速度很慢。
所以我打算写一个存储过程,因为它很高效。可能吗 ??如果可能的话,请给我一个示例代码,在此先感谢......
【问题讨论】:
-
删除中断和格式化代码
-
在存储过程中需要一个临时表,然后才有可能。然而,在类似的情况下,我简单地在(祖先、子级、级别)上维护了一个(冗余)表,然后只需要一个快速查询。
-
你说它变慢了,你还记得mysql表上正确的索引吗?
-
你知道最高等级吗?也许最大级别是父级的不同计数,您可以使用php创建一个sql查询(许多子查询),您不需要存储过程或维护一个加表。
-
@joop,你给我举个例子??
标签: php mysql codeigniter stored-procedures recursion