次の名前のテーブルがあります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>
これを行うには、2 つの 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
}
}
?>
そこで、ここで問題が発生します。
これは、パフォーマンスの面で非常に悪いアプローチです。正しい方法は何ですか。
親の ID を子のユーザー クエリのパラメーターとして使用しようとすると、
bind_param()
関数に関するエラーが発生します。これは、操作を伴う 1 つの SQL クエリのみで実行できます
JOIN
。しかし、私はどうすればよいかわかりません。