I am trying to use a simple MySQL query to update my table with positions. Let's assume I have a book table with an ID, a writer_id and a position field.
I want to be able to have positions from 1 ... x , but per writer_id. If I delete a record there will be a gap in my positions so this is why I want a simple query to reset all the positions without gaps.
Currently I have the following code (which works), but I think this should be possible a lot easier (and probably faster).
set @position := 0;
set @lastDependency := 0;
set @previousDependency := -1;
UPDATE `book` SET
`writer_id`=(@lastDependency:=`writer_id`), -- Set writer_id of current row
position=(
IF (
NOT @lastDependency=@previousDependency,
@position:=1, -- New writer_id => set position to 1
@position:=@position+1 -- Same writer id, increment position
)
),
`writer_id`=(@previousDependency:=`writer_id`) -- Set writer_id of last used row
ORDER BY `writer_id`, position ASC -- Order by current positions
I can also use PHP to loop through all my records and save them one by one, but I guess that won't be any better