【问题标题】:is it possible to write this recursive loop in a MySQL stored procedure是否可以在 MySQL 存储过程中编写此递归循环
【发布时间】:2012-07-21 01:34:45
【问题描述】:

嗨,我正在使用 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);

  • 如您所见,这是一个递归函数。当子层级增长时,效率低下,查询速度很慢。

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

【问题讨论】:

  • 删除中断和格式化代码
  • 在存储过程中需要一个临时表,然后才有可能。然而,在类似的情况下,我简单地在(祖先、子级、级别)上维护了一个(冗余)表,然后只需要一个快速查询。
  • 你说它变慢了,你还记得mysql表上正确的索引吗?
  • 你知道最高等级吗?也许最大级别是父级的不同计数,您可以使用php创建一个sql查询(许多子查询),您不需要存储过程或维护一个加表。
  • @joop,你给我举个例子??

标签: php mysql codeigniter stored-procedures recursion


【解决方案1】:

MySQL 存储过程的缺点多于优点。恕我直言,您应该非常小心地考虑使用此功能。

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

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

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

如果我遇到你的情况,我会做的就是将数据提取出来并在 php 中完成递归处理。

【讨论】:

    猜你喜欢
    • 2010-11-10
    • 2010-10-30
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    相关资源
    最近更新 更多