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.
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 .
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With