表格
id | term | parent | prev_id | title
---+------+--------+---------+-------
1 | 2015 | 2 | 0 | red child
2 | 2015 | 0 | 0 | 2015 parent
3 | 2015 | 2 | 0 | green child
4 | 2015 | 2 | 0 | blue child
-----------------------------+------------
5 | 2016 | 0 | 1 | red child
6 | 2016 | 0 | 2 | 2016 parent
7 | 2016 | 0 | 3 | green child
8 | 2016 | 0 | 4 | blue child
每年都在前进,数据被复制过来。 prev_id
字段将更新为上一个字词的上一个ID,但parent
字段已清除,需要使用新的父ID进行更新。我有一种感觉,我需要一个子查询,但我仍然坚持从这里开始。这可能很容易,而且我正在过度思考......
select a1.id prev_id,
a1.term prev_term,
a1.parent prev_parent,
a2.id new_id,
a2.term new_term,
a2.parent new_parent
from table a1,
table a2
where a1.id = a2.prev_id
预期产出:
id | term | parent | prev_id | title
---+------+--------+---------+-------
1 | 2015 | 2 | 0 | red child
2 | 2015 | 0 | 0 | 2015 parent
3 | 2015 | 2 | 0 | green child
4 | 2015 | 2 | 0 | blue child
-----------------------------+------------
5 | 2016 | 6 | 1 | red child
6 | 2016 | 0 | 2 | 2016 parent
7 | 2016 | 6 | 3 | green child
8 | 2016 | 6 | 4 | blue child
答案 0 :(得分:0)
首先,您需要摆脱在WHERE
子句中列出表的做法。它的语法已经过时了20多年,并且容易出错。明确JOIN
你的桌子在一起。总是
我确定设计本身存在问题,根据您使用的模式判断,但在不知道系统要求的情况下,除此之外我不能说太多。< / p>
关于您的查询,以下内容可以满足您的需求:
UPDATE NEW_CHILD
SET
parent = NEW_PARENT.id
FROM
My_Table NEW_PARENT
INNER JOIN My_Table OLD_PARENT ON
OLD_PARENT.id = NEW_PARENT.prev_id AND
OLD_PARENT.parent = 0
INNER JOIN My_Table OLD_CHILD ON
OLD_CHILD.parent = OLD_PARENT.id
INNER JOIN My_Table NEW_CHILD ON
NEW_CHILD.parent = NEW_PARENT.id AND
NEW_CHILD.prev_id = OLD_CHILD.id
WHERE
NEW_PARENT.parent = 0 AND
NEW_PARENT.term = '2016'