I'm reseting a sort column that has duplicate or missing values like so:
set @last='';
set @sort=NULL;
update conf_profile set sort=
if(
@last=(@last:=concat(org_id,',',profile_type_id,',',page,',',col)),
(@sort:=@sort+1),
(@sort:=0)
)
order by org_id,profile_type_id,page,col,sort,id;
(Go through all the rows sorted by a number of key fields assigning progressively incremented values to sort; whenever any of those fields change, restart at 0.)
It seems to work only if the @sort variable was created prior to doing the update (though it doesn't matter what it was set to). Without the 'set @sort', all the sort values are set to either 0 or NULL.
Any ideas why this would be so? MySQL version 5.0.51.
Update: To explain the logic more at length: on the first row, the @last=(@last:=...) will always be false, and thereafter it will be false when any of the key fields changes from the previous row. (N.B. none of the key fields being concat'd are ever NULL). When it's false, we start the sort counter over again at 0 (@sort:=0), otherwise, it is incremented (@sort:=@sort+1) and the new value is used.
In no case is @sort used before it is being set in the update statement, so whether or how it is set before the update statement should make no difference.