I have two tables a source and a destination. I want to flag the destination table to be updated if any of the corresponding columns in source columns are different. The columns can be null.
Currently this seems very clumsy:
UPDATE destination d
JOIN source s
ON d.id = s.id
SET d.updateFlag = 1
WHERE ( (d.col1 IS NULL AND s.col1 IS NOT NULL)
OR (d.col1 IS NOT NULL AND s.col1 IS NULL)
OR (d.col1 <> s.col1)
)
OR
( (d.col2 IS NULL AND s.col2 IS NOT NULL)
OR (d.col2 IS NOT NULL AND s.col2 IS NULL)
OR (d.col2 <> s.col2)
)
...etc...
OR
( (d.colN IS NULL AND s.colN IS NOT NULL)
OR (d.colN IS NOT NULL AND s.colN IS NULL)
OR (d.colN <> s.colN)
)
Ideally I could do something like:
UPDATE destination d
JOIN source s
ON d.id = s.id
SET d.updateFlag = 1
WHERE HASH(d.col1,d.col2,...etc...,d.colN) <> HASH(s.col1,s.col2,...etc...,s.colN)
Some additional info. The columns are all different data types (some ints, some bits, some strings) and we are using a flavor of MySQL 5.1.
You can simplify your statement by using the NULL-safe equal to operator:
As an alternative, you can use a UNION to find duplicate rows:
You can then use the result from that in your update query: