开发者

Mysql adjacency list model alternative?

I used the adjacency list model for my table in MySQL, along with a PHP function recursion to query and realised it slows down the website. Is there an alterna开发者_运维技巧tive model i could use that i can use one query to get both parent and child elements, without recursion?

The table structure is like this:

    myTable:
+----+----------+
| id | parentID |
+----+----------+
|  1 |     null |
|  2 |        1 |
|  3 |        1 |
|  4 |        2 |
|  5 |        4 |
-----------------

I'm using a recursion query like below:

function  queryf($id) {

$query = mysql_query("SELECT * FROM `Table` WHERE id='$id'",$this->connect);
while($row = mysql_fetch_assoc($query)) {

$sid = $row['id'];
//code
$this->$queryf($sid);
}

}


You can use nested sets approach.

See more info in http://en.wikipedia.org/wiki/Nested_set_model and Move node in nested set


How many records are you storing in your table? Nested sets are definitely faster but the table structure is very delicate. If it breaks it is very challenging to fix the table structure and it generally requires manual intervention.

If you only have a few hundred records, you are probably better off with the Adjacency method. If you are talking about thousands or records, definitely better off with nested sets but make sure the code for handling it is 100% bulletproof or your table will be like Humpty Dumpty.

Although adjacency lists are inefficient, there are methods of using them efficiently. I wrote a class for easy handling of Adjacency lists. You can download it from here:

http://www.pdvictor.com/en/?sv=&category=just%20code&title=adjacency%20model


If you are recursively querying the DB multiple times (which apparently is the case), you will have performance issues.

What you can do is query all the data at once and then let PHP handle/organize the items recursively. You should be fine with that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜