我想将两个看起来像这样的表合并到一个表中,并将重复的键行合并到合并表中的最旧setAppSearchData()
值。
DateAdded
是(Key1,Key2)
。
PRIMARY KEY
答案 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;