1

What is the best way to assign orders to mysql table rows? If I have rows 1 to 5 and I want to remove 4, how can I make 5 the new 4? If I make make 3 the new 1, I need to add 1 to each of the other rows. There could be 1 or 2 rows or a hundred.

Is there a simpler way than manually programming each contingency?

Thanks in advance.

additional: I have an interface where I add packages for customers to see. They are automatically ordered ascending by id. I can reorder them by price, package name, or whatever, but I want to arbitrarily order them by my own preference from time to time.

Thanks again.

5
  • Is the position a unique field in your database or not? Commented Oct 11, 2012 at 2:47
  • don't ever reuse primary id's Commented Oct 11, 2012 at 2:52
  • @Dagon order doesn't have to be primary Commented Oct 11, 2012 at 2:53
  • I added an order field, independent of id, and am about to program it the long way, but hoped someone had a better way. Commented Oct 11, 2012 at 2:54
  • sort by ORDER, but don't use the order id in the db as the displayed order counter. or in other words don't mix the logic of data structure with the business requirement of some numbering system. Commented Oct 11, 2012 at 2:55

3 Answers 3

3

Assuming you have a unique order_column column in your database:

To add a new row at position x:

  • Lock tables
  • update all rows where position >= x and add 1
  • Then insert the new row at position x
  • Unlock tables

To swap positions x and y:

  • UPDATE table SET x=(@temp:=x), x = y, y = @temp;

(source)

To remove a row at position x:

  • Lock tables
  • Remove row at position x
  • update all rows where position > x and subtract 1
  • Unlock tables

To display data:
Just ORDER BY by the order_column column.

Sign up to request clarification or add additional context in comments.

3 Comments

If you're going to down vote at least tell me what's wrong with my answer.
This is very well a possible answer to this question (which is unclear).
Yea, this is the best answer. Thank you for taking the time to point me the right way Mike.
1

Basic approaches to ordering usually amount to ordering on a specific column either alphabetically or numerically. Alternatively if the the order that you need can not be created based on the data you have then you need to add a column exculisevly for ordering purposes, then create an interface to populate that with data. Sounds like you need to do the later.

Comments

0

Unless I completely misunderstood the question:

Leave the table alone and just use ORDER BY to determine sorting when SELECTing rows.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.