Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql compare two tables and display only the difference

Tags:

sql

mysql

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.

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.

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

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

like image 837
Laci K Avatar asked Jul 05 '15 12:07

Laci K


People also ask

How can I find the difference between two tables in MySQL?

First, use the UNION statement to combine rows in both tables; include only the columns that need to compare. The returned result set is used for the comparison. Second, group the records based on the primary key and columns that need to compare.

How can I compare two columns in different tables in MySQL?

Here's the generic SQL query to two compare columns (column1, column2) in a table (table1). mysql> select * from table1 where column1 not in (select column2 from table1); In the above query, update table1, column1 and column2 as per your requirement.


1 Answers

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
like image 53
Pரதீப் Avatar answered Sep 19 '22 00:09

Pரதீப்