分层查询优势

Hierarchical Query Advantages

我有一些巨大的数据库表,里面填满了科学名称,在 parent-child 关系中,就像这样...

TAXON | PARENT
Mammalia | Chordata
Carnivora | Mammalia
Canidae | Carnivora
Canis | Canidae
Canis-lupus | Canis

我安装了 PostgreSQL 并开始处理分层查询,但它比我想象的要复杂得多。所以我想坚持使用 MySQL 并回到我原来的方案,它看起来像这样:

TAXON | PARENT | FAMILY | ORDER
Mammalia | Chordata | (NULL) | (NULL)
Carnivora | Mammalia | (NULL) | Carnivora
Canidae | Carnivora | Canidae | Carnivora
Canis | Canidae | Canidae | Carnivora
Canis-lupus | Canis | Canidae | Carnivora

看起来很业余,但我惊讶地发现生命目录显然使用相同的方案,列数更多,行数超过一百万。

使用此方案,我可以通过简单地计算匹配 Table.Family > 犬科的物种数量来计算 children 和 grandchildren。我可以使用一系列 "stairstep" 查询来找出曾祖父母的名字等

所以我想知道分层查询的好处是什么。它们更优雅,您大概可以只用一个或两个查询来完成所有事情,而不是一系列查询。我还假设它们更快,尽管我的原始查询(带有两个额外字段)已经足够快了。

分层查询是否有一些额外的显着优势可以证明我雇人来设置一个,还是主要只是速度问题?

如果按分层查询,你指的是Postgresql Common Table Expressions;答案是它们是一个很棒的功能,可以让您编写更具可读性的查询,并且在某些(但不是全部)情况下可以提高性能。

真的值得雇人帮你安装 postgresql 吗?也许,也许不是。没有基准很难说。

您真正应该尝试的是:Modified Pre order Tree Traversal 现在听起来很复杂,但实际上并不

We’ll start by laying out our tree in a horizontal way. Start at the root node (‘Food’), and write a 1 to its left. Follow the tree to ‘Fruit’ and write a 2 next to it. In this way, you walk (traverse) along the edges of the tree while writing a number on the left and right side of each node. The last number is written at the right side of the ‘Food’ node. In this image, you can see the whole numbered tree, and a few arrows to indicate the numbering order.

这是另一篇关于它的优秀文章。 http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

这种方法在postgreql和mysql中都可以使用,并且可以轻松转换现有数据。

递归/分层查询实际上通常更慢。它有所不同 - 有更多的行,但另一方面每一行要小得多。

主要优势是灵活性,而不是性能。在您的 table 中,您有一定数量的列...但是如果最终父级(根)和最终子级(叶)之间存在任意数量的可能步骤怎么办?或连接和打开的分支,以便一个对象有两个父对象?这就是分层查询变得更有用的时候。