特里
您几乎在正确的轨道上。您几乎偶然发现了将层级数据存储在数据库中的“ LTREE”系统。您只需要进行一些修改。就这样。
您的表可能如下所示:
CREATE TABLE Table1 (`id` int, `parent_id` int, `name` varchar(13), `path` char(10), `money` int);
您的数据可能看起来像这样。
(1, 0, 'company 1', '1', 10),(2, 1, 'child 1', '1.1', 10),(3, 2, 'child 2', '1.1.1', 10),(4, 1, 'child 3', '1.2', 10,),(4, 1, 'company 2', '2', 10),(4, 1, 'child 2.1', '2.1', 10)
路径列有助于确定哪个公司是另一个公司的子公司。请注意,您实际上并不需要一
allmoney列。这是动态生成的。
您如何找到属于第一家公司的所有资金?
select sum(money) from Table1 where path >= '1' and path < '2'
注意,在我们创建的结构中,child1是child2的父级。那么我们如何找到child1的钱呢?
select sum(money) from Table1 where path >= '1.1' and path < '1.2'
只有一个查询,没有递归。
MPTT
另一种流行的获取分层数据的方法是使用修改后的顺序树遍历。多年来,Sitepoint上有一篇出色的文章,它解释了如何使用大量示例代码来完成此工作。



