0

I have a query that updates the db using EVENT SCHEDULER. Its supposed to update data once a day. My issue is that I can't get it to update if the record exists unless I create UNIQUE INDEX which I can't do since the domain repeats for each month.

INSERT INTO f_s.s_d_s_tab(month,count_per_month,updated)
SELECT * FROM 
(
SELECT
DATE_FORMAT(`FE`,'%m') AS Month, COUNT(FE) AS FirstCount, domain
FROM rets
GROUP BY DATE_FORMAT(`FE`,'%m'), domain
ORDER BY domain, Month ASC
) a
ON DUPLICATE KEY UPDATE count_per_month = a.FirstCount, updated = NOW();

records show like so

Domain    Month    coun_per_month
dom1       01        50
dom1       02        90
dom1       03        34
dom2       01        12
dom2       02        99
dom2       03        80

etc....

what can I do to make it insert new domains but update old ones.

4

2 回答 2

2

我的问题是,如果记录存在,我无法更新它,除非我创建 UNIQUE INDEX,因为域每个月都会重复,所以我不能这样做。

当然可以 -在域和月份上创建一个多列唯一索引。

于 2012-12-12T19:45:49.313 回答
1

它看起来不像 SELECT 列表中的列与 INSERT 列表中的列“对齐”。

INSERT INTO f_s.s_d_s_tab(domain, month, count_per_month, updated)
SELECT a.*
  FROM (
         SELECT r.domain                 AS domain
              , DATE_FORMAT(r.`FE`,'%m') AS month
              , COUNT(r.FE)              AS count_per_month
              , NOW()                    AS updated
           FROM rets r
          GROUP
             BY DATE_FORMAT(r.`FE`,'%m')
              , r.domain
          ORDER BY r.domain ASC, r.month ASC
       ) a
    ON DUPLICATE KEY
UPDATE count_per_month = VALUES(count_per_month)
     , updated         = VALUES(updated)

要生成“重复键”条件以获取 UPDATE 操作,您需要定义一个 UNIQUE 约束(或 PRIMARY KEY)ON f_s.s_d_s_tab (domain, month)

于 2012-12-12T21:00:36.603 回答