我需要从它的祖先计算后代的深度。当一个记录有 时object_id = parent_id = ancestor_id
,它被认为是一个根节点(祖先)。我一直在尝试WITH RECURSIVE
使用 PostgreSQL 9.4运行查询。
我不控制数据或列。数据和表架构来自外部源。该表正在不断增长。现在每天大约有 3 万条记录。树中的任何节点都可能丢失,并且它们将在某个时候从外部源中拉出。它们通常按created_at DESC
顺序拉取,但数据是通过异步后台作业拉取的。
我们最初对这个问题有一个代码解决方案,但现在有 500 万行以上,几乎需要 30 分钟才能完成。
示例表定义和测试数据:
CREATE TABLE objects (
id serial NOT NULL PRIMARY KEY,
customer_id integer NOT NULL,
object_id integer NOT NULL,
parent_id integer,
ancestor_id integer,
generation integer NOT NULL DEFAULT 0
);
INSERT INTO objects(id, customer_id , object_id, parent_id, ancestor_id, generation)
VALUES (2, 1, 2, 1, 1, -1), --no parent yet
(3, 2, …
Run Code Online (Sandbox Code Playgroud)