multiple auto increment in mysql

ε祈祈猫儿з 提交于 2019-12-28 04:32:10

问题


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 column should auto increment when the row is inserted. Then a user will be able to change the sort_order value. But mysql does not allow auto increment for more than one column?

What is the best way to auto increment the sort_order value?

By popular Request, some more explanation.

In administration area, the user will have a list of categories. Using javascript the user can drag the order they want the categories in. The script then posts a list of all the ids in the new order, and the sort_order values in the old order.

I then have a php function which updates mysql with the new sort_order value.

All of this is already done, except I had manually filled out all the sort_order values. I want it to be able to have a value when a user creates a new category.

Then I can use the sort_order to display the category order correctly on the front end.

I have everything done already. But in development I manually filled in the values for the sort_order.


回答1:


You could use a trigger, cf http://dev.mysql.com/doc/refman/5.1/de/create-trigger.html




回答2:


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)



回答3:


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.




回答4:


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.




回答5:


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)



来源:https://stackoverflow.com/questions/7085275/multiple-auto-increment-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!