Domanda

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?

È stato utile?

Soluzione

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;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top