Mysql – SQL update query with join and subquery

MySQL

I am trying to update the values of a column to the results of a sub query. I get the error that the sub query is returning more that one row, which it should. It should be returning a column of values.

Update companies
set c_c_score = ( select t.summ 
              from ( select sum(case when b.hot_tip = 1 
                                     then ((@maxrank-c.rank)/(@maxrank-1)) * (b.score-3) 
                                     else 0 
                                     end) as summ
                     from companies a
                     left join table2 b
                         on a.id = b.company_id
                     left join table3 c
                         on b.table3_id = c.id
                     group by a.id ) AS t);

The sub query runs fine by itself.

    select a.id,  sum(case when b.hot_tip = 1 then ((@maxrank-c.rank)/(@maxrank-1)) * (b.score-3) else 0 end)
        from companies a
        left join table2 b
        on a.id = b.company_id
        left join table3 c
        on b.table3_id = c.id
        group by a.id;

Best Answer

This seems to work:

Update companies c
inner join (select a.id as company_id, sum(case when b.hot_tip = 1 then ((@maxrank-c.rank)/(@maxrank-1)) * (b.score-3) else 0 end) as cc_score
from companies a
left join table2 b
on a.id = b.company_id
left join table3 c
on b.table3_id = c.id
group by a.id) x ON x.company_id = c.id
set c.c_c_score = x.cc_score;