【发布时间】: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中的YoungestGroupId和OldestGroupId列的名称表明它们应该是AgeGroups的外键,这不是您描述的逻辑。你的逻辑对吗?