2

我正在尝试从另一个表中的另一个字段的总和更新一个表中的字段。

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

这两个表由 company_tbl.PRIMARY = location_tbl.companyID 链接

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

我收到“无效使用组功能”的错误

一家公司可以有多个地点

我想做的事可能吗?我想获取属于特定公司的位置总和,并用总和更新 companySize。

谢谢!

4

2 回答 2

9

利用:

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

...或者您可以使用 view,其中包含:

   SELECT c.primary,
          COALESCE(SUM(lt.locationsize), 0) AS companysize
     FROM company_tbl c
LEFT JOIN location_tbl lt ON lt.companyid = c.primary
于 2010-06-18T18:10:25.230 回答
2

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.

于 2010-06-18T19:14:32.573 回答