2013-07-25 201 views
0

我有一个命名为People表:Mysql的选择在嵌套循环

id | name |parent_id 
---+------+--------- 
1 | John | 0 
2 | Jane | 1 
3 | James| 1 
4 | Jack | 0 
5 | Jim | 4 
6 | Jenny| 4 

因此,约翰是简和詹姆斯的父母。树是这样的。

John 
-Jane 
-James 
Jack 
-Jim 
-Jenny 

我要让这似乎是

<table border="1"> 
    <tr> 
     <th colspan="2">John</th> 
    </tr> 
    <tr> 
     <td>-</td><td>Jane</td> 
    </tr> 
    <tr> 
     <td>-</td><td>James</td> 
    </tr> 
    <tr> 
     <th colspan="2">Jack</th> 
    </tr> 
    <tr> 
     <td>-</td><td>Jim</td> 
    </tr> 
    <tr> 
     <td>-</td><td>Jenny</td> 
    </tr> 
<table> 

要做到这一点,我用两个SQL查询的表。这里是伪代码:

<?php 

$firstQuery = 'SELECT id, name FROM People WHERE parent_id = 0'; 

start creating the table 

while ($rowP = $result_parent->fetch()) 
{ 
    //get the child rows using the second query in the loop: 

    $secondQuery = 'SELECT id, name FROM People WHERE parent_id = $rowP["id"]'; 

    start creating table rows for child items. 

    while ($rowC = $result_child->fetch()) 
    { 
     add names into the table belonging the current parent person 
    } 
} 

?> 

所以问题在这里上升。

  1. 这是在性能方面非常糟糕的做法。什么是正确的方法。

  2. 当我尝试使用父母的身份证号作为子人查询的参数时,我收到有关bind_param()函数的错误。

  3. 这可以只执行一个SQL查询与JOIN操作。但我不知道该怎么办。

回答

0

我已经解决了这个问题:

所以基本想法是在while循环中使用fetch()方法。相反,我得到的所有结果集之前的循环再使用它的一个新的实例在foreach循环:

<?php 
    $firstQuery = 'SELECT id, name FROM People WHERE parent_id = 0'; 

    $resultP->setFetchMode(PDO::FETCH_ASSOC); 

    $resultP = $db->exec($firstQuery); 

    $rowP = $resultP->fetchAll(); 

    $foreach($rowP as $rp) 
    { 
     //get the child rows using the second query in the loop: 

     $secondQuery = 'SELECT id, name FROM People WHERE parent_id = :p1'; 

     //start creating table rows for child items. 

     $resultP = $db->prepare($secondQuery); 

     $resultP->bindValue(':p1', $rp["id"], PDO::PARAM_INT); 

     $resultP->setFetchMode(PDO::FETCH_ASSOC); 

     $resultP->exeecute(); 

     $rowC = $resultC->fetchAll(); 

     $foreach($rowC as $rc) 
     { 
      //add names into the table belonging the current parent person 
     } 
    } 
?> 
1

这是在性能asppect非常糟糕的做法。什么是正确的方法。

它实际上不是。
几个主键查找永远不会造成任何伤害。

当我尝试使用父人的id作为子人查询的参数时,出现关于bind_param()函数的错误。

首先,你不只是的错误消息,但阅读理解它,同时为客户提供在这里,充分和完整无缺。

接下来,对于这一个,它很容易猜到。使用store_result()

这只能通过JOIN操作完成一个SQL查询。但我不知道该怎么办。

甚至已经MySQL的官方文档的一部分,一旦规范文本:Managing Hierarchical Data in MySQL(对谷歌第一个结果,顺便说一句)

+0

我知道,网页,但没有什么事情弄清楚我的问题。 – zkanoca