2017-04-10 74 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

哦,是的,這使得總體感覺最後評估時間戳。接得好。 –

相關問題