Well this is going to sound like a lame question, I know. This is probably one of the most obvious things to do, but I’ve been trying to come up with a good way of sorting entries in database.
Image table looking like this:
entry_id | entry_data
-------------------------
1 | data1
2 | data2
... | ...
n | datan
entry_id is of course Primary Key with AI option so all entries have a unique id.
Now. I want to order that data. Say I want entry_id = 2 to be first without changing its entry_id. Then the table needs another column to store order number.
I tried 2 approaches.
-
entry_order_no: this will basically keep order number of the items. Any new item will be always added to the end.
-
left_id + right_id: this approach is used by phpBB. Not sure why it requires right_id though?
I seem to prefer the 1st approach, but how do you sort the data later.
Let’s assume I want to newly added item move from the last position, to say 2nd.
Way I’ve been doing it I was using indexed tables, where index was order no. Each index contained associative array, that had entry_id. That way I “simply” did foreach loop with an UPDATE on all entries from 2nd place down. That may work for few rows. Maybe even tens. But what when you have hundreds? This seems highly inefficient then. Second one seems a bit better. But something still tells me there’s a better approach.
Please do suggest.
I’m not sure the true nature of why you’re trying to do this, so it’s kind of hard to say, but as far as your inefficient foreach loop, stop using iterative methods on sets – use set operations, they’re way faster and exactly what a DB was meant for. so instead of…
do this…
Also, pulling from what Alex Martelli said, doing that should be pretty ok for awhile, but eventually you’ll have to restack everything with new spacing….but a clustered index on that field would keep things in order by that ID….of course it also means inserts to the middle of the table could be resource intensive if it’s a large table.