Question

I have a table called followers that looks like this:

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

How do i create the column growth_rate that is dependent on 2 rows from the column total_fans? Please see the col growth_rate. The numbers in there is what i am trying to get.

Here is my sql query if what i am trying to achieve but there is a problem with my syntax.

UPDATE followers 
SET growth_rate=Total_fans/(Total_fans where id = id-1);
Was it helpful?

Solution

The intuitive way to do this is:

UPDATE followers f
    SET growth_rate=Total_fans/(select Total_fans from followers f2 where f2.id = f.id-1);

But that, alas, won't work in MySQL because of some complicated prohibition against including the table being updated in a subquery in an update statement. Instead, use the join syntax:

update followers f left outer join
       followers f2
       on f2.id = f.id - 1
    set f.growth_rate = f.Total_Fans / f2.Total_Fans;

Then, keep your fingers crossed that Total_fans is never 0. Or, check for this explicitly:

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top