سؤال

I want to update a column whose value is 0 to maximum of that column (In single query).

There are lots of records with 0 value.

I am doing this:

UPDATE table SET field = (SELECT MAX(field) + 1) WHERE field = 0;

But it updates each record to same value. Can we get max value on each row update?

هل كانت مفيدة؟

المحلول

You seem to want to increment the value starting with the next possible value. Here is one method:

update table t cross join
       (select @rn := max(field) from table) var
    set t.field = (@rn := @rn + 1)
    where field = 0;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top