mysql

Change all rows by increasing by a number, but not over a certain value


UPDATE score SET points =  red_chips WHERE red_chips > current_turn

I want to have points be equal to several different chip colours combined, but the MAXIMUM any individual chip colour can give you points must be limited by the current_turn, if the chip colour is higher it should default to only adding the current_turn.

UPDATE score SET points =  red_chips + blue_chips + green_chips + yellow_chips + white_chips

^ this but with EACH colour individually limited by the current_turn as a maximum amount.

I am looking for a way to do this without having to make a new query for each chip colour.


Solution

  • I think what you're looking for is LEAST(current_turn, [xyz]_chips). This will use the chip value if it is less than current_turn but the value of current_turn if the chip value is greater than that.

    That is, if you want points to be equal to the sum of all of chip values with each limited to the value of current_turn, you want something like this:

    UPDATE score SET points = LEAST(current_turn, red_chips) + LEAST(current_turn, blue_chips) + LEAST(current_turn, green_chips) + LEAST(current_turn, yellow_chips) + LEAST(current_turn, white_chips)
    

    That's assuming that the [xyz]_chips values contain the actual net value (correcting for the value of each color). Depending on what current_turn represents relative to the chip values/colors you may want to multiple by the chips relative values. But if what you're looking for a count of the chips, not necessarily accounting for color, or if the [xyz]_chips column contains a color-adjusted value, then you should be fine.

    Also, to clarify a bit about my edit, MIN is a aggregate function that acts on columns finding the minimum value from the rows. LEAST is takes two or more arguments and returns the one with the smallest value (or NULL if any of them are NULL), so it acts on the values of each individual row.