Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple auto increment in mysql

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.

like image 214
dardub Avatar asked Aug 16 '11 21:08

dardub


People also ask

Can we have 2 auto increment in MySQL?

MySQL server already provides two auto increment variables: auto_increment_increment and auto_increment_offset, which can be used to generate different auto increment values on each member.

How many columns can we have with AUTO_INCREMENT?

AUTO_INCREMENT / IDENTITY constraints can take between 0 and three arguments. These arguments let you specify the column's start value, how much it increments or decrements, and how many unique numbers each node caches per session.

How many columns can we have with auto increment in MySQL?

But unfortunately there can be only one AUTO_INCREMENT column per table in MySQL. :-/ So this situation belongs to a class of problems known as MAX+1 problems.

How can I get next auto increment number in MySQL?

MySQL has the AUTO_INCREMENT keyword to perform auto-increment. The starting value for AUTO_INCREMENT is 1, which is the default. It will get increment by 1 for each new record. To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT.


1 Answers

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)
like image 66
Karolis Avatar answered Sep 22 '22 22:09

Karolis