简体   繁体   中英

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 .

在此处输入图片说明

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

  • as you can see this is a recursive function . when the sub levels are growing , iti is inefficient , and make the query very slow .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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