PostgreSQL:更新时忽略了左外部自我连接 [英] PostgreSQL: update with left outer self join ignored

查看:160
本文介绍了PostgreSQL:更新时忽略了左外部自我连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用TRUE更新列leaf_category的列,其中该类别不是父类别.它用作选择语句:

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;

但是,相应的UPDATE将所有列设置为TRUE.

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;

像这样的UPDATE可能吗?

推荐答案

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

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;

此表单具有NOT EXISTS的可能会更快,同时执行以下操作:

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
    );

这篇关于PostgreSQL:更新时忽略了左外部自我连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆