I have a "Sort order" column in my table where user's can order the data based on intregal value.For an example:[album]albumiduseridalbum_namesort_orderIn the front-end UI interface, users can move an album's "sort order" left or right (just like in facebook, myspace etc). The problem is, how do I write the SQL to PROPERLY do this without messing up?Last night, I tried to solve it but couldn't.This is the SQL I came up with:DECLARE @Id INT; SET @Id = 16260610;DECLARE @ToId INT;DECLARE @ToOrderNumber INT;DECLARE @CurrentRecordOrderNumber INT;DECLARE @TempOrder INT;SELECT @CurrentRecordOrderNumber = [order] FROM album WHERE id = @id;SELECT * FROM album WHERE id IN ( SELECT MAX(id) FROM album WHERE id <@Id AND userid = 1 AND groupid IS NULL ) AND groupid IS NULL;SELECT @ToId = id, @ToOrderNumber=[order] FROM album WHERE id IN ( SELECT MAX(id) FROM album WHERE id <@Id AND userid = 1 AND groupid IS NULL ) AND groupid IS NULL;SET @TempOrder = @CurrentRecordOrderNumber;SET @CurrentRecordOrderNumber = @ToOrderNumber;SET @ToOrderNumber = @TempOrder;SELECT @CurrentRecordOrderNumber, @ToOrderNumber, @ToIdIF( NOT @ToId IS NULL )BEGINUPDATE album SET [order] = @CurrentRecordOrderNumber WHERE id = @Id;UPDATE album SET [order] = @ToOrderNumber WHERE id = @ToId;SELECT 1ENDSELECT * FROM album WHERE userid = 1 AND groupid IS NULL ORDER BY [order] ASC;
Sample Result Set:id userid groupid name desc status order16260617 1 NULL sad123 asdsadsadas 0 116260605 1 NULL asd sadasdsa 0 316260610 1 NULL sad asdsadasd 0 416260616 1 NULL 1 1 0 516260618 1 NULL sad sadsadsad 0 616260620 1 NULL dasdsad sdas 0 7The problem is, if I tell record 16260605 to move PREVIOUS of the previous record, it won't move because there is NO record previous than 16260605 (16260605 is the MIN record id in the table for that userid)Can someone help me build the proper sort order sql or even algorithm?