【问题标题】:MySQL Insert new row based on multiple other rows for every company idMySQL根据每个公司ID的多个其他行插入新行
【发布时间】:2013-12-02 03:32:50
【问题描述】:

我有许多公司(数百家)的 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
  • 公司编号
  • 月龄

CombinedAgeGroups

  • 公司编号
  • YoungestGroupId
  • OldestGroupId
  • MaxGroupSize

因此,在 CombinedAgeGroups 表中,我需要为每个公司提供一行。如何遍历所有公司,从每个公司的 AgeGroups 表中取出最年轻的组和最老的组,然后将这些值插入到 CombinedAgeGroups 中?

【问题讨论】:

  • CombinedAgeGroups 中的YoungestGroupIdOldestGroupId 列的名称表明它们应该是AgeGroups 的外键,这不是您描述的逻辑。你的逻辑对吗?

标签: mysql sql


【解决方案1】:

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

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

【讨论】:

  • 谢谢。我最终编写了一个临时 PHP 脚本来执行此操作,但看起来这也可以。
  • @Vincent:很公平......但鉴于我的回答是在您提出问题后仅 3 分钟发布的,有人想知道您为什么要费心问! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多