简单地说,我有一个包含 2 个字段(idDevice 和 timestampReported)的 MySQL 表。
目前我这样做是为了插入一条记录:
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
有没有办法做到这一点?
最佳答案
这是一个解决方案(未测试):
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;
阅读更多:
关于mysql - "replace into"仅当新记录具有新时间戳时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43333417/