I need to compare 2 columns in a table and give 3 things:
- Count of rows checked (Total Rows that were checked)
- Count of rows matching (Rows in which the 2 columns matched)
- Count of rows different (Rows in which the 2 columns differed)
I’ve been able to get just rows matching using a join on itself, but I’m unsure how to get the others all at once. The importance of getting all of the information at the same time is because this is a very active table and the data changes with great frequency.
I cannot post the table schema as there is a lot of data in it that is irrelevant to this issue. The columns in question are both int(11) unsigned NOT NULL DEFAULT '0'. For purposes of this, I’ll call them mask and mask_alt.
Note the elegant use of
sum(condition).This works because in mysql
trueis1andfalseis0. Summing these counts the number of times the condition istrue. It’s much more elegant thancase when condition then 1 else 0 end, which is the SQL equivalent of codingif (condition) return true else return false;instead of simplyreturn condition;.