我有一个命名为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
}
}
?>
所以问题在这里上升。
这是在性能方面非常糟糕的做法。什么是正确的方法。
当我尝试使用父母的身份证号作为子人查询的参数时,我收到有关
bind_param()
函数的错误。这可以只执行一个SQL查询与
JOIN
操作。但我不知道该怎么办。
我知道,网页,但没有什么事情弄清楚我的问题。 – zkanoca