Mysql在嵌套循环中选择

时间:2013-07-25 11:00:19

标签: php pdo mysqli

我有一个名为People的表格:

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. 当我尝试使用父人的id作为子人查询的参数时,我收到有关bind_param()函数的错误。

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

2 个答案:

答案 0 :(得分:1)

  

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

实际上并非如此 一些主键查找永远不会造成任何伤害。

  

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

首先,您不仅提及错误消息,而是读取理解,并在此处提供,已满和未切割。

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

  

这只能通过JOIN操作进行一次SQL查询。但我不知道该怎么做。

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

答案 1 :(得分:0)

我已经解决了这个问题:

所以基本的想法是在fetch()循环中使用while方法。相反,我在循环之前获取所有结果集,然后在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
        }
    } 
?>
相关问题