How can I compare two tables with same structure and find unmatched records with mySQL?

不想你离开。 提交于 2019-12-25 08:11:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!