问题
I have two tables with same structure.
TABLE-1
--------
ID NAME
1 AAAA
2 BBBB
3 CCCC
4 DDDD
TABLE-2
--------
ID NAME
1 AAAA
2 BBBB
3 CCCC
4 DDDD
5 eeee
6 ffff
7 gggg
8 hhhh
9 iiii
How I can compare this tables with MySQL and adding unmatched rows from TABLE-2 in TABLE-1?
回答1:
Insert into table-1 (select id,name from table-2 where id not in (select id from table-1));
回答2:
If any of the ID, NAME is defined as unique key or combined unique (e.g primary key (ID, NAME)) Then its possible to utilize INSERT IGONRE .. SELECT
INSERT IGNORE INTO TABLE1 SELECT * FROM TABLE2
If they are key, duplicate columns will be ignored while inserting as we are using INSERT IGNORE
回答3:
I find the answer. This code working correctly and returnig unmatched rows.
SELECT * FROM TABLE-1
WHERE TABLE-1.ID
NOT IN (
SELECT TABLE-2.ID
FROM TABLE-2
WHERE TABLE-2.ID=TABLE-1.ID
)
来源:https://stackoverflow.com/questions/9584885/how-can-i-compare-two-tables-with-same-structure-and-find-unmatched-records-with