Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql update table from another table

I'm trying to update a field in one table, from the sum of another field, in another table.

company_tbl (PRIMARY, companySize, companyName) location_tbl (PRIMARY, companyID, locationSize, locationName)

The two tables link by company_tbl.PRIMARY = location_tbl.companyID

update company_tbl comp, location_tbl loc
set companySize = sum(locationSize)
where comp.PRIMARY = loc.companyID

I'm getting an error of 'invalid use of group function'

A company can have multiple locations

Is what I want to do possible? I want to take the sum of locations, that belong to a specific company, and update the companySize with the sum.

Thanks!

like image 740
Since_2008 Avatar asked May 18 '26 08:05

Since_2008


1 Answers

Use:

UPDATE company_tbl comp
   SET companySize = (SELECT SUM(lt.locationSize)
                        FROM location_tbl lt
                       WHERE lt.companyid = comp.primary)

...or you could use a view, containing:

   SELECT c.primary,
          COALESCE(SUM(lt.locationsize), 0) AS companysize
     FROM company_tbl c
LEFT JOIN location_tbl lt ON lt.companyid = c.primary
like image 90
OMG Ponies Avatar answered May 19 '26 23:05

OMG Ponies



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!