Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to auto_increment a field in MySQL that is not primary key

Right now, I have a table whose primary key is an auto_increment field. However, I need to set the primary key as username, date (to ensure that there cannot be a duplicate username with a date).

I need the auto_increment field, however, in order to make changes to row information (adding and deleting).

What is normally done with this situation?

Thanks!

like image 571
littleK Avatar asked Jul 20 '09 00:07

littleK


People also ask

Can I auto increment a column that is not a primary key?

There can be only one AUTO_INCREMENT column per table, it must be indexed, and it cannot have a DEFAULT value. So you can indeed have an AUTO_INCREMENT column in a table that is not the primary key.

Does auto increment have to be primary key?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

How do you set a field as auto increment in MySQL?

In MySQL, the syntax to change the starting value for an AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = start_value; table_name.

Can you auto increment varchar in MySQL?

AutoIncrement fields are integer in mysql. You can mirror the auto-increment field in a varchar field and create a trigger which updates the varchar field on insert/update.


2 Answers

Just set a unique index on composite of (username, date).

ALTER TABLE `table` ADD UNIQUE INDEX `name` (`username`, `date`); 

Alternatively, you can try to

ALTER TABLE `table` DROP PRIMARY KEY, ADD PRIMARY KEY(`username`,`date`); 

and I think in the latter case you need those columns to be declared NOT NULL.

like image 111
Artem Russakovskii Avatar answered Sep 21 '22 19:09

Artem Russakovskii


I know this is old question, here is how i solved the problem -

ALTER TABLE `student_info` ADD `sn` INT(3) UNIQUE NOT NULL AUTO_INCREMENT FIRST         
like image 26
Abiaeme Johnson Avatar answered Sep 21 '22 19:09

Abiaeme Johnson