I am looking for a way to only insert when the row does not exist in MySQL, and update when the row exists AND the version of the existing row is less than (or equal to) the version of the new row.
For example, the table is defined as:
CREATE TABLE documents (
id VARCHAR(64) NOT NULL,
version BIGINT UNSIGNED NOT NULL,
data BLOB,
PRIMARY KEY (id)
);
And contains the following data:
id version data
----------------------------
1 3 first data set
2 2 second data set
3 5 third data set
And I want to merge the following table (UPDATE: id column is unique):
id version data
----------------------------
1 4 updated 1st
3 3 updated 2nd
4 1 new 4th
And it should produce the following (UPDATE: see how only 1 is updated and 4 is inserted):
id version data
----------------------------
1 4 updated 1st
2 2 second data set
3 5 third data set
4 1 new 4th
I've looked at INSERT ... ON DUPLICATE KEY UPDATE ... statement, but it doesn't allow for some sort of WHERE clause. Also, I can't really use REPLACE because it also does not allow WHERE. Is this even possible with a single MySQL statement?
I am using Java and am trying to possible insert/update many records using the PreparedStatement with batching (addBatch). Any help would be appreciated.
UPDATE: Is there any way to use this query with the PreparedStatement in Java? I have a List of Document objects with id, version, and data.