问题
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