[英]MySQL Insert new row based on multiple other rows for every company id
I have a MySQL database with many companies (several hundred). 我有一个包含许多公司(数百家)的MySQL数据库。 For each company I need to insert a single row in a new table that combines data from two rows in another table. 对于每个公司,我需要在新表中插入一行,该表将另一表中两行的数据合并在一起。 Kind of like this: 有点像这样:
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
}
My table structure is (basically) as follows: 我的表结构(基本上)如下:
Companies 公司介绍
AgeGroups 年龄组
CombinedAgeGroups 合并年龄组
So in the CombinedAgeGroups table I will need to end up with a single row for each company. 因此,在CombinedAgeGroups表中,我需要为每个公司最后一行。 How do I loop through all the companies, get the youngest group and the oldest group out of the AgeGroups table for each company, and insert those values into CombinedAgeGroups? 如何遍历所有公司,如何从AgeGroups表中为每个公司获取最年轻的组和最老的组,然后将这些值插入CombinedAgeGroups中?
You can use INSERT ... SELECT
with a grouped query: 您可以对分组查询使用INSERT ... SELECT
:
INSERT INTO CombinedAgeGroups (
CompanyId, YoungestGroupId , OldestGroupId
)
SELECT CompanyId, MIN(AgeInMonths), MAX(AgeInMonths)
FROM AgeGroups
GROUP BY CompanyId
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.