Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL compare two tables and return rows that have the same primary key but different data in other fields

Tags:

sql

mysql

I have two structurally identical tables, table2 is a staging ground for new data that will be used in bulk updating table1.

I need to find out which rows would be updated in table1. I want to ignore those rows that would be inserted and those that would be deleted. I'm just interested in the updated rows, where the primary key stays the same but one or more of the other fields in the row contains different data.

So far the closest I have come is the following statement.

SELECT table2.* FROM table2
INNER JOIN table1
ON table1.primarykey = table2.primarykey
WHERE table1.field1 != table2.field1
OR table1.field2 != table2.field2
OR table1.field3 != table2.field3

This returns 0 rows.

EDIT: The query actually works. There was a problem with the data itself. I'm going to go facepalm for a while.

Thank you everyone for your input.

like image 540
Mancmaniak Avatar asked Feb 24 '12 16:02

Mancmaniak


People also ask

How can I get matched and unmatched records from two tables in SQL?

To get all of the rows from just one of the tables – the matched rows as well as the unmatched rows – you need to use the LEFT JOIN or the RIGHT JOIN .

How do you compare two columns values in two different tables in SQL?

Using joins to compare columns by priority among the table. For example, left join returns all values from the first table and null value for the not-matched records from the second table. Similarly, we can use right join, inner join, full join and self join as per our requirements.


1 Answers

One thing that your not accounting for is nulls. This may or may not be your problem as it depends on the data

SELECT table2.* FROM table2
INNER JOIN table1
ON table1.primarykey = table2.primarykey
WHERE table1.field1 != table2.field1
      OR table1.field2 != table2.field2
      OR table1.field3 != table2.field3
      OR (table1.field1 is null and table2.field1  is not null)
      OR (table2.field1 is null and table1.field1  is not null)
      OR (table1.field2 is null and table2.field2  is not null)
      OR (table2.field2 is null and table1.field2  is not null)
      OR (table1.field3 is null and table2.field3  is not null)
      OR (table2.field3 is null and table1.field3  is not null)
like image 115
Conrad Frix Avatar answered Oct 05 '22 11:10

Conrad Frix