繁体   English   中英

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

[英]is it possible to write this recursive loop in a MySQL stored procedure

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

在此处输入图片说明

通过父级标题时,我将获得所有子级值。

这是代码

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

  • 如您所见,这是一个递归函数。 当子级增长时,iti效率低下,并使查询非常慢。

所以我打算写一个存储过程,因为它很有效。 可能吗 ?? 请给我看一个示例代码,如果可能的话,谢谢...................

MySQL存储过程比利弊更多。 恕我直言,您应谨慎使用此功能。

主要缺点之一是无法对其进行版本控制。 您只有一个版本,仅此而已。

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

考虑到缺点,您还应该考虑以下事实:使用存储过程没有其他好处-没有性能提高。 娜达!

如果您遇到这种情况,我将要做的只是提取数据并在php中进行递归处理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM