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

岁酱吖の 提交于 2019-11-29 01:04:51

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.

Abiaeme Johnson

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         

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);

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