Provided that I have the following result set from a mysql database table:
+----+------+-------+
| ID | type | value |
+----+------+-------+
| 8 | A | 1435 |
| 9 | B | 7348 |
| 10 | A | 1347 |
| 11 | A | 3478 |
| 12 | A | 4589 |
| 13 | B | 6789 |
+----+------+-------+
I would like to delete row ID 8 and push the values in the field ‘value’ down, in such a way that every row has the value of previous entry, but affecting only those where the field ‘type’ is the same as the row being deleted (‘A’ in this case).
That is to say, deleting row id 8 should eventually yield the following:
+----+------+-------+
| ID | type | value |
+----+------+-------+
| - | - | - | *
| 9 | B | 7348 | |
| 10 | A | 1435 | * |
| 11 | A | 1347 | * |
| 12 | A | 3478 | * |
| 13 | B | 6789 | V
+----+------+-------+
ID 10 has inherited the value from ID 8, then ID 11 inherits from ID 10, and so on. Notice however how rows having type ‘B’ are unaffected.
So the question: Is there any way to perform this “shift” of values without having to query and update each row one by one? In an ideal world I would do one query to do shift and then another to delete the row, but I’m not quite sure if this is possible at all.
(Also I would rather not use Triggers, since I intend encapsulate all the application logic within the application itself)
See it on sqlfiddle.
UPDATE
I hadn’t realised you actually wanted to update the underlying table. For that, you can use some slight hackery to effectively do the same thing in an
UPDATEstatement (one can’t assign to user variables directly, so instead assign to a column the concatenation of its new value and a null string formed from taking the first 0 characters of the newly assigned user variable):See it on sqlfiddle.