views:

42

answers:

2

Hi, 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!

+4  A: 

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
OMG Ponies
A little update to your query.WHERE lt.companyid = comp.primaryOr else every companySize will be the same :-)So I take it it's not possible to do the update with this syntax?update company_tbl comp, location_tbl locset companySize = sum(locationSize)where comp.PRIMARY = loc.companyIDJust out of curiosity, I like learning new things :-)
Idealflip
@Idealflip: If there's no table alias (generally aren't accepted on UPDATE statements), then column references without a table alias are for the table that does not have any alias defined.
OMG Ponies
You should use the view. Unless you absolutely need to optimize for reads on company size, it's better to compute it each time. If you can calculate the value of one column from another, you're setting yourself up for a situation where the two values are out of sync.
Kendrick
A: 

First initialize the companySize to zero:

UPDATE company_tbl SET companySize = 0; 

Then for each matching location row, add the locationSize:

UPDATE company_tbl comp JOIN location_tbl loc ON comp.PRIMARY = loc.companyID
SET comp.companySize = comp.companySize + loc.locationSize;

You get the desired sum by the time it has processed all the matching locations for each company.

Bill Karwin