Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UPDATE table with SELECT from another but with a field being SUM(someField)

Tags:

sql

mysql

Basically I have something like this:

UPDATE
    Table
SET
    Table.col1 = other_table.col1,
FROM
    Table
INNER JOIN
    other_table
ON
    Table.id = other_table.id

The problem is that I would like to update col1 with the select being like:

SELECT SUM(col1) FROM other_table WHERE Table.id = other_table.id AND period > 2011

Edit

Correct Answer:

UPDATE bestall  
INNER JOIN (SELECT bestid,SUM(view) as v,SUM(rawView) as rv 
                           FROM beststat 
                           WHERE period > 2011 GROUP BY bestid) as t1 
ON bestall.bestid = t1.bestid
SET view = t1.v, rawview = t1.rv
like image 342
dynamic Avatar asked Dec 05 '25 02:12

dynamic


1 Answers

You can't use aggregates directly in a set clause. One way around that is a subquery:

update  your_table as yt
left join 
        (
        select  id
        ,       count(*) as cnt
        from    other_table
        where   period < 4
        group by
                id       
        ) as ot
on      yt.id = ot.id 
set     col1 = coalesce(ot.cnt,0)

Example at SQL Fiddle.

like image 197
Andomar Avatar answered Dec 06 '25 15:12

Andomar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!