1

I have a main table that I use in my application called t_media. The dataset is from an external source that is updated every day. I download the dataset to a temporary table called t_media_temp every day. I need to do three things:

  • Insert a record from t_media_temp into t_media if it doesn't already exist
  • Update a record in t_media if the date is different in t_media_temp
  • Delete a record from t_media if it does not exist in t_media_temp

In the current situation I use the 3 queries beneath, but is there an easy way to combine it into a single query?

/* Insert */
INSERT INTO t_media (`col_1`, `col_2`, `col_3`, `col_x`) 
SELECT (`col_1`, `col_2`, `col_3`, `col_x`) 
FROM t_media_temp AS t1 
WHERE NOT EXISTS ( 
    SELECT * FROM t_media AS t2 
    WHERE t1.col_1 = t2.col_1 
)

/* Update */
UPDATE t_media, t_media_temp SET 
    t_media.col_1 = t_media_temp.col_1, 
    t_media.col_2 = t_media_temp.col_2, 
    t_media.col_3 = t_media_temp.col_3, 
    t_media.col_x = t_media_temp.col_x 
WHERE
    t_media.col_1 = t_media_temp.col_1 
AND 
    t_media.col_2 != t_media_temp.col_2

/* Delete */
DELETE FROM t_media WHERE col_1 NOT IN ( SELECT col_1 FROM t_media_temp )

col_1 is always a unique value in the table.

1
  • why logic around t_media.col_2 != t_media_temp.col_2 absent in insert query? Commented Jul 25, 2015 at 20:19

1 Answer 1

2

According to documentation https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

You can mix your INSERT and UPDATE like this:

INSERT INTO t_media (`col_1`, `col_2`, `col_3`, `col_x`) 
SELECT (`col_1`, `col_2`, `col_3`, `col_x`) 
FROM t_media_temp AS t1
ON DUPLICATE KEY UPDATE
    t_media.col_2 = t1.col_2, 
    t_media.col_3 = t2.col_3, 
    t_media.col_x = t3.col_x 

But there is no way to mix INSERT or UPDATE with DELETE

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

3 Comments

Is col_1 automatically recognised as the duplicate key? And there is another condition... It has to be updated only is col_2 doesn't match.
@web_student yes, col_1 will be automatically recognised as dupe if its a unique key (or part of it). abut col_2 i ve asked before. why we not see workaround it in your INSERT query? is it any key in table structure? can you post original fields names, not col_X?
what do you mean workaround in INSERT query? There is only one unique identifier and that is col_1. All the other values may not be unique. The table consists of 50+ columns.

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.