SQL - 如果EXISTS UPDATE ELSE INSERT

时间:2014-03-20 19:15:18

标签: mysql sql mysql-workbench

我有以下查询:

INSERT INTO distance (deviceID,datum,tavolsag)
 SELECT 
deviceID, DATE(FROM_UNIXTIME(timestamp)) as datum, 
sum(case when distanceKM/1000<416 then distanceKM/1000 else 0 end) as tavolsag
FROM eventdata 
GROUP BY datum,deviceID;

我想知道每天运行查询时如何避免数据重复/或使用“if exists update else insert”方法。

THX

2 个答案:

答案 0 :(得分:0)

试试这个:

 INSERT INTO distance (deviceID,datum,tavolsag)
 SELECT deviceID,datum,tavolsag from(select 
deviceID, DATE(FROM_UNIXTIME(timestamp)) as datum, 
sum(case when distanceKM/1000<416 then distanceKM/1000 else 0 end) as tavolsag
FROM eventdata 
GROUP BY datum,deviceID)t
on duplicate key update set datum=......, tavolsag = .....

答案 1 :(得分:0)

如果你对(deviceID,datum)有一个UNIQUE约束,那么你可以使用INSERT ... ON DUPLICATE KEY

INSERT INTO distance (deviceID, datum, tavolsag)
SELECT d.deviceID
     , DATE(FROM_UNIXTIME(d.timestamp)) as datum
     , SUM(CASE WHEN d.distanceKM/1000<416 
                THEN d.distanceKM/1000
                ELSE 0 END
       ) AS tavolsag 
  FROM eventdata d
 GROUP BY datum, deviceID
ON DUPLICATE KEY
UPDATE tavolsag = VALUES(tavolsag)

当执行此语句时,这将尝试插入,如果插入会违反唯一键约束,而不是抛出错误,MySQL将执行UPDATE,相当于:

UPDATE distance
   SET tavolsag  = ?
 WHERE device_id = ?
   AND datum     = ?

如果存在多个唯一约束,则操作取决于标记为违反的唯一约束。执行的实际更新将相对于抛出错误的唯一约束。