开发者

Insert based on two elements existing in a row MySQL

I'm imagining that this is a simple question, but I'm running into syntax issues I think.

I have a table that has an event ID as primary key(eventID), a device ID that of what triggered the event, and a timestamp of when the event triggered. I"m processing the mySQL(5.1) elements via C# and command line.

My dilemma is that I have to duplicate/import the database to another database and I am getting duplicate entries due to the eventID being the primary key and it being upd开发者_如何转开发ated everytime a new record is added automatically. Changing that isn't an option. So what I want to do is only insert into the database if my current deviceID+timestamp combination doesn't already exist.

I've found a lot of query examples, but they either throw syntax issues or simply don't work as needed. In pseudo code this is what I'm looking for..

IF timestampToInsert EXISTS WHERE deviceIDtoInsert ALSO EXISTS ON SAME ROW
     UPDATE ROW
ELSE
     INSERT INTO myTABLE (deviceID, timeStamp) VALUES (deviceIDtoInsert, timestampToInsert)


It sounds like you want to do an "upsert".

In MySQL this is called "INSERT...ON DUPLICATE KEY UPDATE":

INSERT INTO myTABLE (deviceID, timeStamp)
VALUES (deviceIDtoInsert, timestampToInsert)
ON DUPLICATE KEY UPDATE ...

Note this will only work if you have a unique index on (deviceID,timestamp)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜