MySQL DUPLICATE KEY UPDATE + SUM函数

时间:2013-11-10 09:38:23

标签: mysql sql

我正在尝试构建一个表来汇总“缓存”表中的数据。 因为我计划每隔几分钟运行一次聚合查询(通过cron或事件,不重要),并且为了避免重复行,我希望我的汇总表中已存在的行将被更新(我已经配置了一个唯一的密钥),因此我的“缓存”表中的值只会与现有值集成。

这是我的问题:

INSERT INTO  `ReportsSummary` 
                (`date`,
                `txtID`,
                `webID`,
                `GEO`,
                `OSS`,
                `impressions`,
                `clicks`)

SELECT DATE_FORMAT(date ,'%Y-%m-%d'),txtID,webID, GEO, OSS,
    SUM( if(actionType = '1',1,0) ) as add_impressions,
    SUM( if(actionType = '2',1,0) ) as add_clicks
FROM `CacheReports` as t GROUP BY txtID,webID,GEO,OSS

ON DUPLICATE KEY UPDATE
impressions = impressions + (`t`.`add_impressions`),
clicks = clicks + (`t`.`add_clicks`);

干杯

1 个答案:

答案 0 :(得分:3)

表t(CacheReports)中没有add_impressions和add_clicks列 - 它是包含它们的聚合。使用以下更正的查询:

INSERT INTO  `ReportsSummary` 
                (`date`,
                `txtID`,
                `webID`,
                `GEO`,
                `OSS`,
                `impressions`,
                `clicks`)

SELECT * FROM (
  SELECT DATE_FORMAT(date ,'%Y-%m-%d'),txtID,webID, GEO, OSS,
    SUM( if(actionType = '1',1,0) ) as add_impressions,
    SUM( if(actionType = '2',1,0) ) as add_clicks
FROM `CacheReports` as t GROUP BY txtID,webID,GEO,OSS) AS `u`

ON DUPLICATE KEY UPDATE
impressions = impressions + `u`.`add_impressions`,
clicks = clicks + `u`.`add_clicks`;