更新 SQL mptt 表中的所有父 ID
考虑一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,我找到了一种方法:
不确定这是否是最有效的方法,但它足够快。
Actually, I found a way to do it:
Not sure if its the most efficient way to do it but it's fast enough.