I have a small doubt, how to manage the following situation. In a DB table i save the relevant data in different columns and at the end i save the exact order in a column ca
I'd create a table to save the results, in my example/solution the table to save is called 'ladders' and the data comes from 'data', and it limits by the top 100 entries. It first clears the table, then sets the temporary position variable to 0 and starts increasing/inserting.
"TRUNCATE `ladders`";SET @pos:=0;
INSERT INTO `ladders` ( `identifier`,`pos`,`score`)"
" SELECT `id` , @pos := @pos + 1 , `thescore`"
" FROM `data` ORDER BY `thescore`"
" DESC LIMIT 100";
When you say: "change the position to the rows", do you mean moving rows up and down through the table (relative to position
ordering)?
If so, to move the row up, you need to exchange the position
with previous row. To move it down, you need to do the same with the next row. Depending on your particular SQL dialect, the syntax for exchanging values from different rows will probably look similar to this:
UPDATE YOUR_TABLE
SET position =
CASE position
WHEN 2 THEN 3
WHEN 3 THEN 2
END
WHERE position IN (2, 3)
This example moves the row 3 up and row 2 down. Replace 2 and 3 according to your needs...
BTW, this should work even if there is a UNIQUE constraint on position
(confirmed under Oracle).
For more ideas, you may take a look at this question.