"替换成"只有新记录有最新的时间记录

时间:2017-04-10 21:48:10

标签: mysql mysqli

简单地说,我有一个包含2个字段的mysql表(idDevice和timestampReported)。

目前我这样做是为了插入记录:

replace into example_lastevent
    SET
    timestampReported =     1523395565, -- april 10 2017
    idDevice=3

我现在尝试做的是修改此查询,因此如果之前的记录具有更高(更新)的时间戳,则不会更新。我尝试了以下没有工作

replace into example_lastevent
SET
timestampReported = if(timestampReported > 123456, timestampReported,123456) -- 02 Jan 1970 (SHOULD NOT BE EXECUTED)
idDevice=3

有没有办法做到这一点?任何帮助都是非常苛刻的。

1 个答案:

答案 0 :(得分:1)

这是一个解决方案(未经测试):

INSERT INTO example_lastevent
  SET timestampReported = 1523395565, idDevice=3
ON DUPLICATE KEY UPDATE
  timestampReported = GREATEST(timestampReported, VALUES(timestampReported));

我认为idDevice是表的唯一键。没有理由在ON DUPLICATE KEY子句中设置它,因为它必须是相同的。

如果您有其他列,请使用CASE:

INSERT INTO example_lastevent
  SET timestampReported = 1523395565, otherColumn='ABC123', idDevice=3
ON DUPLICATE KEY UPDATE
  timestampReported = GREATEST(timestampReported, VALUES(timestampReported)),
  otherColumn = CASE WHEN timestampReported < VALUES(timestampReported) 
                     THEN VALUES(otherColumn) ELSE otherColumn END;

了解更多: