as mysql with 嵌套_Mysql在嵌套循环中选择

bd96500e110b49cbb3cd949968f18be7.png

I have a table named as People:

id | name |parent_id

---+------+---------

1 | John | 0

2 | Jane | 1

3 | James| 1

4 | Jack | 0

5 | Jim | 4

6 | Jenny| 4

So john is parent of Jane and James. Tree goes like this.

John

-Jane

-James

Jack

-Jim

-Jenny

I want to make a table that seems like

John
-Jane
-James
Jack
-Jim
-Jenny

To do this, I use two sql queries. Here is the pseudo-code:

$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

}

}

?>

So the problem rises here.

This is very bad approach in the performance asppect. What is the correct way.

When I try to use the parent person's id as a parameter for the child people query, I get error about bind_param() function.

This can be done only one SQL query with JOIN operation. But I don't know how to do.

解决方案

I have solved the problem:

So the basic idea is about using fetch() method in a while loop. Instead, I get the all resultset before the loop then use a new instance of it in a foreach loop:

$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

}

}

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值