0

I'm triying to upload some files with incremental data. The tabla has a PK (_id), but this _id could appears in many files with different values.

I'd like to load massively the files with a REPLACE INTO or similar, if the register doesn't exist then it must be inserted, but if the register already exists, it must check if the field updated is later than the other one or not, and if it is, replace it, and if it is not, ignore. Is this possible?

I have tried to do several tests with REPLACE and UPDATE or create a temporary table but without results

0

1 Answer 1

0

Use conditional code in the ON DUPLICATE KEY UPDATE clause.

INSERT INTO yourTable
SELECT * 
FROM tempTable
ORDER BY updated
ON DUPLICATE KEY UPDATE 
    col1 = IF(NEW.updated > updated, NEW.col1, col1),
    col2 = IF(NEW.updated > updated, NEW.col2, col2),
    -- repeat for all columns

If you're using pre-8.x MySQL, use VALUES(columnname) instead of NEW.columnname

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks. I assume that the conditional table should not have a PK in the sense that it should allow duplicate values, so that they can then be evaluated.
Do you mean tempTable._id? I assumed it would also be a PK, and it's unique in each file. You would load the file into the temp table, run this query, then empty the table and repeat with other files.
If it can be duplicated in tempTable, and there are multiple rows that satisfy NEW.updated > updated, it's unpredictable which one will be used.
Although you could use ORDER BY updated so it will always use the most recent one.
I had planned to load multiple files into the temp table at the same time; even if they had the same _id, and then run the query. Would that work?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.