将INSERT / DELETE / UPDATE查询合并为一个

时间:2015-07-25 20:05:45

标签: mysql

我在我的应用程序中使用了一个名为t_media的主表。数据集来自每天更新的外部源。我每天都将数据集下载到一个名为t_media_temp的临时表中。我需要做三件事:

  • 将t_media_temp中的记录插入t_media(如果该记录尚不存在)
  • 如果t_media_temp中的日期不同,则更新t_media中的记录
  • 如果t_media_temp
  • 中不存在,则从t_media删除记录

在目前的情况下,我使用下面的3个查询,但是有一种简单的方法可以将它组合到一个查询中吗?

/* 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始终是表格中的唯一值。

1 个答案:

答案 0 :(得分:2)

根据文件https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

您可以将INSERT和UPDATE混合使用,如下所示:

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 

但是没有办法将INSERT或UPDATE与DELETE混合使用