I have the following sortable
table:
| id | txt | position |
|----|-----|----------|
| 1 | aaa | 1 |
| 2 | bbb | 2 |
| 3 | ccc | 3 |
Now I want to change the position order. Say I want to move row 3 to position 1 keeping the order of the other rows intact:
| id | txt | position |
|----|-----|----------|
| 1 | aaa | 2 |
| 2 | bbb | 3 |
| 3 | ccc | 1 |
I can make this happen with this query after updating the row I want to be on top to position 0:
SET @row_number:=0;
UPDATE
sortable,
(
SELECT
@row_number:=ifnull(@row_number, 0)+1 AS new_position,
id
FROM sortable
ORDER BY position
) AS table_position
SET position=table_position.new_position
WHERE table_position.id=sortable.id;
This works perfectly fine when moving a row to the first position. But it gets in trouble when trying to move a row to the second (or any other) position for example.
I'd like some help fixing the query so I can move any row to any position and it'll update the other rows accordingly. So if I move 3 to 2, 2 becomes 3. If I move 1 to 3, 2 becomes 1 and 3 becomes 2. I hope you get the idea. Obviously there will be more rows in the real world data. This is just an example.