UPDATE表,按ID移位

时间:2015-02-03 05:04:18

标签: mysql set insert-update

我希望使用新列更新表,同时引用另一列中的上一行。

ID | Fruit  | Fruit_prev |
-------------------------
1  | Apple  |            |
2  | Orange | Apple      |
3  | Banana | Orange     |
4  | Lemon  | Banana     |

原始表中不存在Fruit_prev,我试图用UPDATE列添加它。

我的想法是:

UPDATE table SET Fruit_prev = (SELECT Fruit WHERE ID = ID-1);

但是,这在MYSQL中不起作用。

实现这一目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

默认情况下更新ID:

UPDATE FruitTable AS ft
INNER JOIN FruitTable AS ft2
    ON ft.ID - 1 = ft2.ID
SET ft.Fruit_prev = ft2.Fruit

按任意列+1移位更新(此处为日期列):

UPDATE
Fruit as t0
INNER JOIN
  (SELECT ft.*, 
         @rownum := @rownum + 1 AS rank
    FROM Fruit ft, 
         (SELECT @rownum := 0) r
  ORDER BY Date) AS t1
INNER JOIN
  (SELECT ft.*, 
         @rownum2 := @rownum2 + 1 AS rank
    FROM Fruit ft, 
         (SELECT @rownum2 := 0) r
  ORDER BY Date) AS t2
ON t0.Id = t1.Id AND t1.rank - 1= t2.rank
SET t0.FruitPrev = t2.Fruit;

这里加入了三张桌子。第一个是默认值,因此它可以更新,第二个和第三个,加上Date的排名,因此它们可以被rank字段移位+1。