简体   繁体   English

Mysql邻接列表模型替代?

[英]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. 我在MySQL中使用了我的表的邻接列表模型,以及用于查询的PHP函数递归,并意识到它减慢了网站的速度。 Is there an alternative 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 http://en.wikipedia.org/wiki/Nested_set_model中查看更多信息并在嵌套集中移动节点

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. 如果您只有几百条记录,那么使用Adjacency方法可能会更好。 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. 如果你正在谈论数千或记录,最好使用嵌套集,但要确保处理它的代码是100%防弹或你的表将像Humpty Dumpty。

Although adjacency lists are inefficient, there are methods of using them efficiently. 虽然邻接列表效率低下,但有一些方法可以有效地使用它们。 I wrote a class for easy handling of Adjacency lists. 我写了一个类来轻松处理Adjacency列表。 You can download it from here: 你可以在这里下载:

http://www.pdvictor.com/en/?sv=&category=just%20code&title=adjacency%20model 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. 你可以做的是一次查询所有数据,然后让PHP递归地处理/组织项目。 You should be fine with that. 你应该没问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM