I have a “reward_points” table with structure similar to ‘id’, ‘user_id’, ‘points’, ‘datetime_gained’.
Each user_id can have multiple rows each with a quantity of reward points. The total value of the points they have available to spend is the sum of all the rows (referenced by their user_id.
When a user spends points, I need to deduct the points from their total starting with the oldest (using the date time_gained field) and progressively using the next oldest until all the points they have just spent have been allocated.
This is obviously quite trivial to do in a scripting language but I’m trying to work out if it can be done using pure MySQL?
Instead of actually subtracting points, given your current transaction-style structure wouldn’t it be better to insert new rows with negative point values? Then a
SUMwill give you the new deducted balance.By deducting straight from the original rows, you’re in effect invalidating that data. If the user gained 5 points on 3/1, then spent 2 points today, the database now says that user gained 3 points on 3/1 (which is incorrect). Adding new rows would show that the user gained 5 points on 3/1 then lost 2 points today.