简体   繁体   English

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

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

hi i am using codeigniter and MySQL i have a table structure like this . 嗨,我正在使用codeigniterMySQL我有一个这样的表结构。

在此处输入图片说明

i am getting all the child values when i pass the parent title . 通过父级标题时,我将获得所有子级值。

this the code 这是代码

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

when i pass display_children('',0); 当我通过display_children('',0); i get 我得到

Food<br>
  Fruit<br>
    Red<br>
      Cherry<br>
    Yellow<br>
      Banana<br>
  Meat<br>
    Beef<br>
    Pork

to display the 'Fruit' subtree, you would run display_children('Fruit',0); 要显示“水果”子树,可以运行display_children('Fruit',0);

  • as you can see this is a recursive function . 如您所见,这是一个递归函数。 when the sub levels are growing , iti is inefficient , and make the query very slow . 当子级增长时,iti效率低下,并使查询非常慢。

so i am planning to write a stored procedure , because it is efficient . 所以我打算写一个存储过程,因为它很有效。 is it possible ?? 可能吗 ?? please show me an example code if it is possible , thanks in advance ................... 请给我看一个示例代码,如果可能的话,谢谢...................

MySQL stored procedures have more cons than pros. MySQL存储过程比利弊更多。 Imho, you should consider using this feature with extreme care. 恕我直言,您应谨慎使用此功能。

One of the major downsides is that it cannot be versioned. 主要缺点之一是无法对其进行版本控制。 You have one version and that's it. 您只有一个版本,仅此而已。

It is evil by design to include business logic inside a storage engine, no matter if it's mysql, oracle, postgre, etc. 在设计上将业务逻辑包含在存储引擎中是邪恶的,无论它是mysql,oracle,postgre等。

Having in mind the cons, you should also consider the fact that you have no added benefit of using stored procedures - no performance gain. 考虑到缺点,您还应该考虑以下事实:使用存储过程没有其他好处-没有性能提高。 Nada! 娜达!

What I would do if I was in your situation is to just pull the data off and have the recursive processing done in php. 如果您遇到这种情况,我将要做的只是提取数据并在php中进行递归处理。

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

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