我正在尝试使用同一个表中的数据更新表path
中的哈希和parType列。我可以从SO的答案中获得以下sql,但更新似乎让我失望。
我在这里尝试做的是更新hash = 0和parType = 0的所有行,hash =相同的行id和parType =该行的父id的类型值。
如果您能看到我想要的结果,那么
你能帮忙吗?别介意我的sql。的Sql
update path t join(
select t1.id, t1.type, t2.parent from path t1, path t2 where t1.parent = t2.id;
) as p on p.id=t.id set hash = t1.id and parType = t1.type;
更新前
"id" "type" "parent" "hash" "parType"
"1" "0" "0" "0" "0"
"2" "2" "1" "0" "0"
"3" "3" "2" "0" "0"
"4" "4" "3" "0" "0"
期望的结果
"id" "type" "parent" "hash" "parType" //parType = the type of the parent
"1" "0" "0" "1" "0"
"2" "2" "1" "2" "0"
"3" "3" "2" "3" "2" -> This is value from the parents type
"4" "4" "3" "4" "3"
编辑 - 这有效,但我仍然不确定这是否是正确的方法
update path a join(
select t1.id as hash, t2.type as parType from path t1 inner join path t2 on t1.parent = t2.id
) b on a.id=b.hash set a.hash = b.hash , a.parType = b.parType;
答案 0 :(得分:1)
这样的东西?
UPDATE table1 t LEFT JOIN
(SELECT t1.id,t1.type FROM table1 t1 INNER JOIN table1 t2 ON t1.id>t2.id GROUP BY t1.id) as p
ON p.id+1=t.id SET t.hash=t.id,t.parType=ifnull(p.type,0)
答案 1 :(得分:0)
请试试这个
update path t join(
select t1.id, t2.type, t2.parent from path t1, path t2 where t1.parent = t2.id;
^^
) as p on p.id=t.id set hash = t1.id and parType = t2.type;
^^
我已将内部联接从t1.type
更改为t2.type
,将ON
条件从parType = t1.type
更改为parType = t2.type
答案 2 :(得分:0)
试试这个
update t set
hash = t.id,
partype = p.type
from path t
left join path p
on p.id = t.parent
where hash = 0
and parType = 0