是否可以在MySQL存储过程中编写此递归循环

时间:2012-07-22 16:28:20

标签: php mysql codeigniter stored-procedures recursion

我正在使用codeigniterMySQL我有一个像这样的表结构。

enter image description here

当我通过父标题时,我获得了所有子值。

这个代码

<?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

要显示“Fruit”子树,您可以运行display_children('Fruit',0);

  • 你可以看到这是一个递归函数。当子级别增长时,iti效率低下,并使查询非常慢。

所以我打算编写一个存储过程,因为它很有效。可能吗 ??如果有可能请告诉我一个示例代码,提前谢谢...................

1 个答案:

答案 0 :(得分:-1)

MySQL存储过程比专业人士更有利。 Imho,你应该考虑非常谨慎地使用这个功能。

其中一个主要缺点是无法进行版本控制。你有一个版本,就是这样。

无论是mysql,oracle,postgre等,将业务逻辑包含在存储引擎中都是邪恶的设计。

考虑到缺点,您还应该考虑到使用存储过程没有额外好处这一事实 - 没有性能提升。纳达!

如果我遇到你的情况,我会做的就是关闭数据并在php中完成递归处理。

相关问题