Mysql比较两个表,只显示差异。

时间:2022-08-18 14:17:14

I would like to find the difference between two tables, because there is a column in table 2 which was linked to the table 1 ID column but sadly a site manager deleted items from table 1 and now there are a lots of unlinked rows in table 2 what causes problems on the site.

我想找两个表之间的区别,因为有一个列在表2与表1 ID列,但遗憾的站点管理器删除从表1的项目,现在有大量的链接行表2是什么原因导致的问题。

For example here are the table structures

例如,这里是表结构

Table 1          table 2

ID | name      ID | value (this is the ID from table 1) 
1  | one       1  | 1
2  | two       2  | 2
3  | three     3  | 4
6  | six       4  | 4
7  | seven     5  | 5
               6  | 5
               7  | 6
               8  | 7
               9  | 1
               10 | 1

As you see in table 2 some IDs from table 1 are in multiple rows and I would like to get all of them which aren't present in table 1 as the return of the query.

正如您在表2中看到的,表1中的一些id位于多个行中,我希望获得表1中没有的所有id作为查询的返回。

Just for clarification this is what I would like to get from the query

澄清一下,这是我想从查询中得到的

Result:

结果:

ID (form table 2) | value
 3                | 4
 4                | 4
 5                | 5
 6                | 5

I know I could use for example NOT IN but than I would have to put in about a 1000 IDs and table 1 contains much more items than what is linked in table 2

我知道我可以不使用,但是我需要输入1000个id表1包含的项比表2中链接的项要多得多

How can I do a query which will return a result like above?

如何执行查询,以返回如上所示的结果?

1 个解决方案

#1


6  

Use NOT EXISTS

使用不存在

select * 
from table2 A
Where Not exists (select 1 from table1 B Where A.ID = B.value)

Or LEFT OUTER JOIN

或左外连接

select *
from table2 A 
LEFT OUTER JOIN table1 B 
on A.ID = B.value
Where B.value IS NULL

#1


6  

Use NOT EXISTS

使用不存在

select * 
from table2 A
Where Not exists (select 1 from table1 B Where A.ID = B.value)

Or LEFT OUTER JOIN

或左外连接

select *
from table2 A 
LEFT OUTER JOIN table1 B 
on A.ID = B.value
Where B.value IS NULL