我有一个以分层方式包含类别的表。
路径列当前为空,但应如下所示:
id parent_id name path
1 (null) vehicles '/vehicles'
2 1 honda '/vehicles/honda'
3 1 toyota '/vehicles/toyota'
4 2 civic '/vehicles/honda/civic'
5 4 dx '/vehicles/honda/civic/dx'
6 (null) airplans '/airplanes'
7 3 camry '/vehicles/toyota/camry'
如何为此表编写更新查询以更新“路径”列?
注意:这是一个单独的查询,它将更新所有行的路径列,并且路径本质上是一个层次结构,因此我确定需要递归。
答案 0 :(得分:2)
with recursive cat_tree (id, parent_id, name, full_path) as (
select id,parent_id,name, '/'||name as full_path
from categories
where parent_id is null
union all
select c.id,c.parent_id,c.name,p.full_path||'/'||c.name
from categories c
join cat_tree p on p.id = c.parent_id
)
update categories
set path = c.full_path
from cat_tree c
where c.id = categories.id;
根据您的使用方式,您可能需要考虑完全删除列path
并根据递归CTE创建视图。
答案 1 :(得分:-1)
我认为一个简单的mysql更新查询将处理这个问题。
试试这个 :
UPDATE '$TABLE_NAME' SET PATH = '$VALUE' WHERE id= '$id';