Mysql

在重複密鑰更新時插入 … (…) (Select…)

  • November 5, 2015

你能幫我解決一個問題嗎。任務是在 MySQL 數據庫中插入一條記錄。條款:

  • 如果記錄存在 - 更新記錄。
  • 如果記錄不存在 - 創建一個新的。

‘NETFLOW’.‘Month’ 表中的關鍵列是:

  • ‘年’
  • ‘月’
  • ‘日’
  • ‘小時’
  • ‘srcaddr’
  • ‘dstaddr’。

事情是盡可能快地查詢,如果可能的話,在一個查詢中。

目前查詢的文本是:

   INSERT INTO `netflow`.`Month` (`Year`, `Month`, `Day`, `Hour`, `srcaddr`,`dstaddr`, `doctets`)
   (
     SELECT 
       YEAR( FROM_UNIXTIME(  `unix_secs` ) ) AS `YEAR`, 
       MONTH( FROM_UNIXTIME(  `unix_secs` ) ) AS `MONTH`, 
       DAYOFMONTH( FROM_UNIXTIME(  `unix_secs` ) ) AS `DAY`, 
       HOUR( FROM_UNIXTIME(  `unix_secs` ) ) AS `HOUR`,  
       `srcaddr` ,  
       `dstaddr` ,  
       `doctets` 
     FROM  `netflow`.`raw` 
       WHERE `unix_secs` <= 1394179200
     GROUP BY 
       `YEAR`, 
       `MONTH`, 
       `DAY`, 
       `HOUR`,
       `srcaddr`,
       `dstaddr`
   )
   ON DUPLICATE KEY UPDATE

...

如果要使用新值更改值,可以使用:

ON DUPLICATE KEY UPDATE 
   doctets = VALUES(doctets) ;

或者,如果您想將新值添加到現有值:

ON DUPLICATE KEY UPDATE 
   doctets = doctets + VALUES(doctets) ;
INSERT INTO `netflow`.`Month` (`Year`, `Month`, `Day`, `Hour`, `srcaddr`,`dstaddr`, `doctets`)
(
 SELECT 
   YEAR( FROM_UNIXTIME(  `unix_secs` ) ) AS `YEAR`, 
   MONTH( FROM_UNIXTIME(  `unix_secs` ) ) AS `MONTH`, 
   DAYOFMONTH( FROM_UNIXTIME(  `unix_secs` ) ) AS `DAY`, 
   HOUR( FROM_UNIXTIME(  `unix_secs` ) ) AS `HOUR`,  
   `srcaddr` ,  
   `dstaddr` ,  
   `doctets` 
 FROM  `netflow`.`raw` 
   WHERE `unix_secs` <= 1394179200
 GROUP BY 
   `YEAR`, 
   `MONTH`, 
   `DAY`, 
   `HOUR`,
   `srcaddr`,
   `dstaddr`
)
ON DUPLICATE KEY UPDATE SET col_name1 = val1, col_name2 = val2

你也可以使用REPLACE INTO. 如果密鑰已經存在,那麼它將更新記錄,否則它將插入一條新記錄。

REPLACE INTO `netflow`.`Month` (`Year`, `Month`, `Day`, `Hour`, `srcaddr`,`dstaddr`, `doctets`)
(
 SELECT 
   YEAR( FROM_UNIXTIME(  `unix_secs` ) ) AS `YEAR`, 
   MONTH( FROM_UNIXTIME(  `unix_secs` ) ) AS `MONTH`, 
   DAYOFMONTH( FROM_UNIXTIME(  `unix_secs` ) ) AS `DAY`, 
   HOUR( FROM_UNIXTIME(  `unix_secs` ) ) AS `HOUR`,  
   `srcaddr` ,  
   `dstaddr` ,  
   `doctets` 
 FROM  `netflow`.`raw` 
   WHERE `unix_secs` <= 1394179200
 GROUP BY 
   `YEAR`, 
   `MONTH`, 
   `DAY`, 
   `HOUR`,
   `srcaddr`,
   `dstaddr`
)

引用自:https://dba.stackexchange.com/questions/60381