问题
I am cloning and extending the Google Tasks application. I want to be able to store the rows order. I have created a field in the database, named rowNumber. When the user inserts a row in the middle of others, I have to update this field in many other rows to achieve the desired output. There is a better way to do it?
BTW the application is made for the Google AppEngine (Python).
回答1:
Make rowNumber a floating point number. When user inserts between rows x and y, the new row gets rowNumber = (x.rowNumber + y.rowNumer) / 2.
When you want to move a row, just update its rowNumber the same way based on target position.
New rows get rowNumber eg. MAX + 256.
Edit Microsoft solved this in SQL Server 2008 using new HierarchyId datatype. You can insert between 2 items almost as many times as you want - until you run out of HierarchyId max size.
回答2:
One option might be to store rows as a linked list, where each row keeps an additional field for the next and previous row. The up side of this is that it requires touching only two other rows following an insert. the downside is that, (as I understand it) AppEngine doesn't have joins, so querying more than one row at a time will be pretty ugly.
来源:https://stackoverflow.com/questions/1151286/what-is-the-best-way-to-store-the-order-between-rows-in-the-database