1

我正在尝试构建一个表格来汇总“缓存”表格中的数据。因为我计划每隔几分钟运行一次聚合查询(通过 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`);

干杯

4

1 回答 1

4

表 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`;
于 2013-11-10T13:07:04.390 回答