Question

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?

Était-ce utile?

La solution

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;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top