Frage

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?

War es hilfreich?

Lösung

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;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top