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

slo*_*oow 3 sql postgresql join sql-update

我想更新的列leaf_categoryTRUE其中的类别是不是一个父类.它作为一个select语句:

 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;
Run Code Online (Sandbox Code Playgroud)

但是,相应的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;
Run Code Online (Sandbox Code Playgroud)

UPDATE这样的可能呢?

Erw*_*ter 9

您只是缺少一个连接的WHERE子句:

UPDATE catalog_category 
SET    leaf_category = TRUE
FROM   catalog_category c1 
LEFT   join catalog_category c2 ON c1.id = c2.parent_id
WHERE  catalog_category.id = c1.id
AND    c2.parent_id IS NULL;
Run Code Online (Sandbox Code Playgroud)

这个带有NOT EXISTS的表单可能更快,同时做同样的事情:

UPDATE catalog_category 
SET    leaf_category = TRUE
WHERE  NOT EXISTS (
    SELECT *
    FROM   catalog_category c
    WHERE  c.parent_id = catalog_category.id
    );
Run Code Online (Sandbox Code Playgroud)

  • @Dems:您可以使用表的别名进行更新,但`c1`关系在`FROM`子句中.在PostgreSQL中,与MySQL不同,一次只能更新*one*表.如果我没有弄错的话,这对应于SQL标准 - 而附加的`FROM`子句是标准的PostgreSQL扩展. (2认同)