slo*_*oow 3 sql postgresql join sql-update
我想更新的列leaf_category与TRUE其中的类别是不是一个父类.它作为一个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这样的可能呢?
您只是缺少一个连接的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)
| 归档时间: |
|
| 查看次数: |
5019 次 |
| 最近记录: |