How to add a primary key to a MySQL table?

前端 未结 10 1155
渐次进展
渐次进展 2020-11-29 18:53

This is what I tried but it fails:

alter table goods add column `id` int(10) unsigned primary AUTO_INCREMENT;

Does anyone have a tip?

相关标签:
10条回答
  • 2020-11-29 19:23

    Existing Column

    If you want to add a primary key constraint to an existing column all of the previously listed syntax will fail.

    To add a primary key constraint to an existing column use the form:

    ALTER TABLE `goods`
    MODIFY COLUMN `id` INT(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT;
    
    0 讨论(0)
  • 2020-11-29 19:25

    This code work in my mysql db:

    ALTER TABLE `goods`
    ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT,
    ADD PRIMARY KEY (`id`);
    
    0 讨论(0)
  • 2020-11-29 19:29

    Not sure if this matter to anyone else, but I prefer the id table to the first column in the database. The syntax for that is:

    ALTER TABLE your_db.your_table ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT FIRST;
    

    Which is just a slight improvement over the first answer. If you wanted it to be in a different position, then

    ALTER TABLE unique_address ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT AFTER some_other_column;
    

    HTH, -ft

    0 讨论(0)
  • 2020-11-29 19:31

    For me, none of suggestions worked giving me the errors of syntax, so I just gave a try using phpmyadmin(version 4.9.2), (10.4.10-MariaDB) and added id column with auto-increment primary key. Id column was nicely added from the first element.

    Query output was:

    ALTER TABLE table_name ADD id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (id);

    0 讨论(0)
提交回复
热议问题