Skip to content
Advertisement

mysql update with if and max

I have lost hours on this and nothing works for me.

I have filed strp_aa that is default NULL. The filed strp_aa should update only if its null with MAX strp_aa + 1, and if its not null if it already has a number it should stay the same.

short version of code is

Also tired

I tried multiple things like this one mentioned here Update MySQL with if condition:

I have also found this mysql query to update field to max(field) + 1 and tried all sorts of combinations with supplied answer and it wont work for me. One of the version is:

This just keep adding one even if there is a number set on strp_aa… I don’t know what else to try.

EDIT: Had s little problem with @GMB answer because all fields are starting with NULL, so max(strp_aa) gives 0 results in case none of the fields had a number in it. I solved that with COALESCE statement and posting it here if someone has similar problem.

Advertisement

Answer

You can use the update ... join syntax for this:

The cross join brings the max value of strp_aa over the whole table. The where clause eliminate row(s) where strp_aa is not null.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement