SQL While循环重复

时间:2013-05-26 07:58:32

标签: sql loops while-loop duplicates

我在我的SQL循环中得到了这个:

PartID:1 Year:2003 ModelID:1375
PartID:1 Year:2004 ModelID:1375
PartID:1 Year:2005 ModelID:1375
PartID:2 Year:1995 ModelID:1244
PartID:2 Year:1996 ModelID:1244
PartID:2 Year:1997 ModelID:1244
PartID:2 Year:1998 ModelID:1244
PartID:2 Year:1999 ModelID:1244
PartID:2 Year:2000 ModelID:1244
PartID:2 Year:2001 ModelID:1244
PartID:2 Year:1996 ModelID:2361
PartID:2 Year:1997 ModelID:2361
PartID:2 Year:1998 ModelID:2361
PartID:2 Year:1999 ModelID:2361
PartID:2 Year:2000 ModelID:2361

但我需要这样的数据库插入(PartId,Start_Year,End_Year,ModelId):

PartID:1 Start Year:2003 End year:2005 ModelID:1375
PartID:2 Start Year:1995 End year:2001 ModelID:1244
PartID:2 Start Year:1996 End year:2000 ModelID:2361

您是否知道如何在SQL While循环或SQL查询中执行此操作。这些是表格:

model2year

id | model_id | year
1          1        1966
2          2        1973
3          2        1972
4          2        1971
5          2        1970

model2year2part

id | model2year_id | part_id
1             9521              1
2             9520              1
3             9519              1
4             8637              2
5             8636              2

这些是示例表:

http://milversite.net/model2year.zip
http://milversite.net/model2year2part.zip

这是上面表格的SQL查询

$result = mysql_query("SELECT * FROM model2year JOIN model2year2part ON model2year2part.model2year_id = model2year.id");

while($row = mysql_fetch_array($result))
{
   $part_id = $row['part_id'];
   $year = $row['year'];
   $model_id = $row['model_id'];
   echo "PartID:$part_id Year:$year ModelID:$model_id<br>";
}

但是我需要在这个结果表中插入没有重复的model_id,而不是年份范围从min。最大为model_id:

result_table

part_id | model_id | start_year | end_year

谢谢!

1 个答案:

答案 0 :(得分:1)

将GROUP BY子句与聚合函数一起使用

SELECT Part_ID, Model_id,
       MIN(YEAR) AS Start_Year, MAX(YEAR) AS End_Year
FROM model2year JOIN model2year2part 
  ON model2year2part.model2year_id = model2year.id
GROUP BY Model_ID, Part_ID