6

我有一张像这样的桌子:

id      |    name    |  profit |  cost  
---------------------------------------
1       |  aaa       | 4       | 2 
2       |  aaa       | 4       | 3 
3       |  aaa       | 4       | 2 
4       |  bbb       | 4       | 1 

我想从此表中删除重复行(根据名称),但在删除之前将已删除行的值添加到剩余行

所以在这种情况下,我希望运行查询后的表如下所示:

id      |    name    |  profit |  cost  
---------------------------------------
1       |  aaa       | 12      | 7 
4       |  bbb       | 4       | 1 

是否可以在 mysql 中执行此操作,而无需创建另一个表并复制数据,因为这是一个大表(100 万行但每天都在增加)?

4

1 回答 1

1

SQLFiddle 演示

首先更新min(id)每行NAME

UPDATE T a JOIN 
(
  SELECT min(ID) as minID,name,SUM(profit) as SP,SUM(cost) as SC 
  FROM T GROUP BY name
) b 
 ON a.id = b.minID 
 SET a.profit = b.sp,a.cost=b.sc;

然后删除行,除了那些min(id)为每个的行NAME

DELETE T
FROM T
LEFT JOIN 
(
  SELECT min(ID) minid ,name FROM T GROUP BY name
) b  
ON t.id = b.minid
WHERE b.minid is NULL
于 2013-11-14T12:56:31.757 回答