2016-08-22 79 views
0

我想合併兩個表,看起來像這樣,放到一個表中,並且用於重複的鍵行,以在合併表中添加最舊的DateAdded值。MySQL - 合併兩個表格 - 條件

(Key1,Key2)PRIMARY KEY

+-----------+-----------+------+-----+-------------------+-----------------------------+ 
| Field  | Type  | Null | Key | Default   | Extra      | 
+-----------+-----------+------+-----+-------------------+-----------------------------+ 
| Key1  | int(10) | NO | PRI |     |        | 
| Key2  | int(10) | NO | PRI |     |        | 
| DateAdded | DATETIME | NO |  |     |        | 
+-----------+-----------+------+-----+-------------------+-----------------------------+ 

回答

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 

UPDATE: 或者,這也應該工作:

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;