gpt4 book ai didi

MySQL根据每个公司ID的多个其他行插入新行

转载 作者:行者123 更新时间:2023-11-29 13:24:36 25 4
gpt4 key购买 nike

我有一个 MySQL 数据库,其中包含许多公司(数百家)。对于每个公司,我需要在一个新表中插入一行,该新表组合了另一个表中两行的数据。有点像这样:

For each company in Companies{
Get min(AgeInMonths) as YoungestGroup from AgeGroups where companyid = company;
Get max(AgeInMonths) as OldestGroup from AgeGroups where companyid = company;
Insert YoungestGroup,OldestGroup,CompanyId into CombinedAgeGroups
}

我的表结构(基本上)如下:

公司

  • 公司 ID
  • 公司名称

年龄组

  • 年龄组 ID
  • 公司 ID
  • 年龄

组合年龄组

  • 公司 ID
  • YoungestGroupId
  • 最旧的组 ID
  • 最大组大小

因此,在CombinedAgeGroups 表中,我需要为每个公司添加一行。如何循环遍历所有公司,从每个公司的 AgeGroups 表中获取最年轻的组和最老的组,并将这些值插入到 JointAgeGroups 中?

最佳答案

您可以使用INSERT ... SELECT使用分组查询:

INSERT INTO CombinedAgeGroups (
CompanyId, YoungestGroupId , OldestGroupId
)
SELECT CompanyId, MIN(AgeInMonths), MAX(AgeInMonths)
FROM AgeGroups
GROUP BY CompanyId

关于MySQL根据每个公司ID的多个其他行插入新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20316227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com