37

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!

Umar Abbas
  • 4,399
  • 1
  • 18
  • 23
littleK
  • 19,521
  • 30
  • 128
  • 188

4 Answers4

24

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.

Artem Russakovskii
  • 21,516
  • 18
  • 92
  • 115
11

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         
kuro
  • 3,214
  • 3
  • 15
  • 31
Abiaeme Johnson
  • 111
  • 1
  • 2
4

Use something like:

CREATE TABLE users (
  id INT PRIMARY KEY AUTO_INCREMENT,
  user VARCHAR(32) NOT NULL,
  thedate DATE NOT NULL,
  UNIQUE(user,thedate)
);

If you already have the table, and just want to add a unique constraint on user+thedate, run

ALTER TABLE users  ADD UNIQUE KEY user_date_idx (user,  thedate);
nos
  • 223,662
  • 58
  • 417
  • 506
1

Change your current primary key to be a unique key instead:

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

The auto_increment will function normally after that without any problems. You should also place a unique key on the auto_increment field as well, to use for your row handling:

ALTER TABLE table ADD UNIQUE KEY(id);
zombat
  • 92,731
  • 24
  • 156
  • 164
  • 2
    I tried to do it this way, however was still getting the error: #1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key – littleK Jul 20 '09 at 01:00