Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to store sort order/priority?

Tags:

sorting

mysql

I'm using MySQL. I have a table where I need to be able to sort manually set the priority/order of the rows. I had originally thought of assigning each row an arbitrary order (1, 2, 3, etc.), then just "swapping" the order with the row being moved, but I don't think this is the best way to do it.

After doing some reading at related questions on here (like this one), a lot of people have said to assign a value to the priority column based off the id column (id * 1000). And to rearrange the rows, you would divide/subtract the difference between the columns. I don't quite understand how this works.

This is the layout of the table I need to sort.

CREATE TABLE liability_detail (
   id int NOT NULL AUTO_INCREMENT,
   analysis_id int NOT NULL, //(many-to-one relationship with analysis table)
   other_columns various datatypes
   sequence int DEFAULT 0
)

I'd like to setup an easy way to manage the priority of rows so I can easily sort them without having to write a lot of code to manage everything.

like image 431
Jeff Avatar asked Jul 16 '12 18:07

Jeff


1 Answers

I ended up following the advice in this question: https://stackoverflow.com/a/6804302/731052

I set the sort-order column = id * 1000 so I could get unique orders. So far this works very well and haven't had any problems with it.

like image 110
Jeff Avatar answered Sep 18 '22 11:09

Jeff