2017-04-10 86 views
1

简单地说,我有一个有两个字段(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 

有没有办法做到这一点?任何帮助都非常令人满意。

回答

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; 

了解更多:

+0

谢谢!是做到了,与小调整:其他列需要在timestampReported之前进行评估,否则(我认为)它计算到新设置的时间戳。所以查询云: INSERT INTO example_lastevent SET timestampReported = 10,DESCR = 'Othercolumn',idDevice = 30 ON DUPLICATE KEY UPDATE DESCR = CASE WHEN timestampReported user7847267

+0

哦,是的,这使得总体感觉最后评估时间戳。接得好。 –

相关问题