在我的数据库中,我将一个树状数据结构保存为一个表tab,其中包含列id(主键)value、from_id和depth,其中depth(整数)表示距树根的距离。
现在我想tab从另一个表candidates(列id, value, from_id)向表中添加行,但有两个限制:1)只有新的id和 2)只有depth低于某个给定阈值的行(例如 3 或 4)。
from_id在那个点上可能有不止一个tab指向 中的新行candidates。
作为 Postgres 初学者,我希望我的方法是正确的,但效率很低:
insert into tab
select distinct c.id, c.value, c.from_id, t.depth+1 as depth
from candidates as c
join tab as t on t.id=c.from_id
where depth<3 and c.id not in
(select id from tab);
我正在寻找加快速度的建议。与一个事务中的其他两个操作一起,对于少于 10k 行,这需要几分钟。
我正在R使用该RPostgres软件包,但我相信这更像是一个 SQL / 数据库问题。