簡體   English   中英

PostgreSQL:忽略左外部自連接的更新

[英]PostgreSQL: update with left outer self join ignored

我想用TRUE更新列leaf_category ,其中類別不是父類別。 它作為一個選擇語句:

 select 
     c1.id, c1.name, c1.slug, c1.level, c2.parent_id, c2.name, c2.slug, c2.level 
 from
     catalog_category c1 
 left outer join 
     catalog_category c2 on 
     (c1.id = c2.parent_id)
 where 
     c2.parent_id is null;

但是,相應的UPDATE將所有列設置為TRUE

update catalog_category 
set leaf_category = True
from
    catalog_category c1 
left outer join 
    catalog_category c2 on 
    (c1.id = c2.parent_id)
 where 
     c2.parent_id is null;

像這樣的UPDATE可能嗎?

您只是缺少一個連接WHERE子句:

UPDATE catalog_category c
SET    leaf_category = true
FROM   catalog_category c1 
LEFT   JOIN catalog_category c2 ON c1.id = c2.parent_id
WHERE  c.id = c1.id
AND    c2.parent_id IS NULL;

帶有NOT EXISTS這種形式可能更快,執行相同的操作:

UPDATE catalog_category c
SET    leaf_category = true
WHERE  NOT EXISTS (
    SELECT FROM catalog_category c1
    WHERE  c1.parent_id = c.id
    );

UPDATE手冊。

有關的:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM