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.
t_media.col_2 != t_media_temp.col_2absent in insert query?