PostgreSQL: update with left outer self join ignored

限于喜欢 提交于 2019-12-23 19:58:45

问题


I want to update the column leaf_category with TRUE where the category is not a parent category. It works as a select statement:

 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;

However, the corresponding UPDATE sets all the columns to 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;

Is an UPDATE like that possible at all?


回答1:


You are just missing a connecting WHERE clause:

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;

This form with NOT EXISTS is probably faster, while doing the same:

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


来源:https://stackoverflow.com/questions/8766763/postgresql-update-with-left-outer-self-join-ignored

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!