I\'m using php and mysql. I have a table with the id column set to auto increment as the primary key. I\'m trying to add another column called sort_order. The sort_order col
You may store 0 in sort_order and then sort by sort_order + id
. Results will be same because sort_order
will be exact 0 instead of id
( less on id
)
You could use a trigger, cf http://dev.mysql.com/doc/refman/5.1/de/create-trigger.html
You can use a trigger to update your row upon insert, or choose an appropriate value in your PHP code at the time the query is produced.
However, you should consider whether you really need to create an auto-incrementing sort_order value. In your display code, you can sort items that have been given an explicit sort order, and place the remaining unsorted items at the appropriate place (bottom?) in the list.
Maybe add a timestamp and sort on that, which actually adds meaning to your data model. A "sort_order" column means you're putting presentation (view) logic into your data model, which is a Bad Thing.
You can leave your sort column equal to NULL by default. The only thing you need is a little smarter query. For instance:
select *
from something
order by ifnull(sort, id)