MySQL - 合并两个表 - 有条件

时间:2016-08-22 14:30:59

标签: mysql merge

我想将两个看起来像这样的表合并到一个表中,并将重复的键行合并到合并表中的最旧setAppSearchData()值。

DateAdded(Key1,Key2)

PRIMARY KEY

1 个答案:

答案 0 :(得分:1)

随意更改表格名称:

INSERT INTO table_merged (Key1, Key2, dateAdded)
SELECT Key1, Key2, MIN(dateAdded) dateAdded
FROM (
    SELECT Key1, Key2, dateAdded
    FROM table1
    UNION ALL
    SELECT Key1, Key2, dateAdded
    FROM table2
  ) a
GROUP BY Key1, Key2  

<强>更新 或者,这也应该有效:

INSERT INTO table_merged (Key1, Key2, dateAdded)
SELECT Key1, Key2, dateAdded
FROM table1
ON DUPLICATE KEY UPDATE
  dateAdded = CASE WHEN VALUES(dateAdded) < dateAdded THEN VALUES(dateAdded) ELSE dateAdded END;

INSERT INTO table_merged (Key1, Key2, dateAdded)
SELECT Key1, Key2, dateAdded
FROM table2
ON DUPLICATE KEY UPDATE
  dateAdded = CASE WHEN VALUES(dateAdded) < dateAdded THEN VALUES(dateAdded) ELSE dateAdded END;