更新 SQL mptt 表中的所有父 ID

发布于 2024-09-13 16:04:30 字数 1007 浏览 5 评论 0原文

考虑一个 SQL 表,它使用 MPTT 存储分层数据(修改后的预购树遍历)方法。

CREATE TABLE node (
    id              SERIAL          NOT NULL, -- primary key

    -- Nested mptt tree model.
    lft             INT             NOT NULL,
    rgt             INT             NOT NULL,

    -- Some legacy applications still need to access parent nodes using a foreign key
    parent_id       INT,

    FOREIGN KEY(parent_id) REFERENCES node
);

现在我想立即更新所有parent_id 外键。不幸的是,我的 SQL 技能真的已经生锈了。谁能指出我一种有效的方法来做到这一点?

这就是我尝试的方式:

UPDATE node AS main 
SET main.parent_id=ss.id 
FROM (
    SELECT parent.id 
    FROM node AS parent 
    WHERE main.lft BETWEEN parent.lft AND parent.rgt
    ORDER BY parent.lft DESC) ss;

不幸的是,这似乎不起作用:

错误:FROM 中的子查询无法引用 到相同查询级别的其他关系

感谢您的任何提示。

PS:如果重要的话,这是在 PostgreSQL 上的。

consider a SQL table, which stores hierarchical data using MPTT (Modified Preorder Tree Traversal) method.

CREATE TABLE node (
    id              SERIAL          NOT NULL, -- primary key

    -- Nested mptt tree model.
    lft             INT             NOT NULL,
    rgt             INT             NOT NULL,

    -- Some legacy applications still need to access parent nodes using a foreign key
    parent_id       INT,

    FOREIGN KEY(parent_id) REFERENCES node
);

Now I'd like to update all the parent_id foreign keys at once. Unfortunately, my SQL skills are really rusted. Can anyone point me to an efficient way to do it?

That's the way I tried it:

UPDATE node AS main 
SET main.parent_id=ss.id 
FROM (
    SELECT parent.id 
    FROM node AS parent 
    WHERE main.lft BETWEEN parent.lft AND parent.rgt
    ORDER BY parent.lft DESC) ss;

Unfortunately, this does not seem to be working:

ERROR: subquery in FROM cannot refer
to other relations of same query level

Thanks for any hints.

PS: This is on PostgreSQL, if it matters.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不乱于心 2024-09-20 16:04:30

实际上,我找到了一种方法:

UPDATE node 
SET parent_id=ss.id 
FROM (
    SELECT id, lft, rgt 
    FROM node ORDER BY lft DESC) ss 
WHERE ss.lft < node.lft AND ss.rgt > node.rgt;

不确定这是否是最有效的方法,但它足够快。

Actually, I found a way to do it:

UPDATE node 
SET parent_id=ss.id 
FROM (
    SELECT id, lft, rgt 
    FROM node ORDER BY lft DESC) ss 
WHERE ss.lft < node.lft AND ss.rgt > node.rgt;

Not sure if its the most efficient way to do it but it's fast enough.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文