我有一个名为followers的表,如下所示:
id FB_fans TW_fans Total_fans growth_rate
1 2 3 5 #5/5=1.0 # this col is currently NULL but i added numbers i wanted in there.
2 3 4 7 #5/7
如何创建依赖于total_fans列中的2行的列growth_rate?请参阅col growth_rate。那里的数字是我想要得到的。
这是我的SQL查询,如果我想要实现但我的语法有问题。
UPDATE followers
SET growth_rate=Total_fans/(Total_fans where id = id-1);
答案 0 :(得分:0)
这样做的直观方法是:
UPDATE followers f
SET growth_rate=Total_fans/(select Total_fans from followers f2 where f2.id = f.id-1);
但是,唉,由于禁止在update
语句中包含正在子查询中更新的表的复杂禁令,因此无法在MySQL中运行。相反,请使用join
语法:
update followers f left outer join
followers f2
on f2.id = f.id - 1
set f.growth_rate = f.Total_Fans / f2.Total_Fans;
然后,保持手指交叉,Total_fans
永远不会0
。或者,明确检查:
update followers f left outer join
followers f2
on f2.id = f.id - 1
set f.growth_rate = (case when f2.Total_Fans > 0 then f.Total_Fans / f2.Total_Fans end);