Reputation: 2327
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.
Upvotes: 1
Views: 394
Reputation: 24363
Assuming you have a unique order_column
column in your database:
To add a new row at position x:
To swap positions x and y:
UPDATE table SET x=(@temp:=x), x = y, y = @temp;
To remove a row at position x:
To display data:
Just ORDER BY
by the order_column
column.
Upvotes: 3
Reputation: 71908
Unless I completely misunderstood the question:
Leave the table alone and just use ORDER BY
to determine sorting when SELECT
ing rows.
Upvotes: 0
Reputation: 56
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.
Upvotes: 1