mysql从另一个表更新表

发布于 2024-09-06 08:43:27 字数 441 浏览 4 评论 0原文

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

company_tbl(主要、公司规模、公司名称) 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。

谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

赠我空喜 2024-09-13 08:43:27

使用:

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

...或者你可以使用视图 ,包含:

   SELECT c.primary,
          COALESCE(SUM(lt.locationsize), 0) AS companysize
     FROM company_tbl c
LEFT JOIN location_tbl lt ON lt.companyid = c.primary

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
感情废物 2024-09-13 08:43:27

首先将 companySize 初始化为零:

UPDATE company_tbl SET companySize = 0; 

然后对于每个匹配地点行,添加 locationSize:

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

在处理完每个公司的所有匹配地点时,您将获得所需的总和。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文