【问题标题】:Mysql Selects in nested loopsMysql 在嵌套循环中选择
【发布时间】:2013-07-25 11:00:18
【问题描述】:

我有一个名为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 查询来完成。但我不知道该怎么做。

【问题讨论】:

    标签: php pdo mysqli


    【解决方案1】:

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

    其实不然。
    一些主键查找永远不会造成任何伤害。

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

    首先,您不仅提及错误消息,而且阅读理解它,并在此处提供,完整并且未删减。

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

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

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

    【讨论】:

    • 我知道那个页面,但没有找到解决我的问题的地方。
    【解决方案2】:

    我已经解决了这个问题:

    所以基本思想是在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
            }
        } 
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-16
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 2019-10-19
      相关资源
      最近更新 更多