Adding a Primary Key to a MySQL Table
Adding a primary key to a MySQL table can be accomplished through specific syntax. However, some users may encounter errors when attempting this operation.
How to Add a Primary Key
To add a primary key to a table, use this syntax:
ALTER TABLE [table_name] ADD PRIMARY KEY ([column_name]);
For example, to add a primary key to the goods table with a column named id:
ALTER TABLE goods ADD PRIMARY KEY (id);
Troubleshooting Common Error
One common error that may occur is when attempting to create a primary key while adding the column. The following syntax will not work:
ALTER TABLE goods ADD COLUMN `id` INT(10) UNSIGNED PRIMARY AUTO_INCREMENT;
To resolve this issue, specify PRIMARY KEY instead of just PRIMARY. The correct syntax is:
ALTER TABLE goods ADD COLUMN `id` INT(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT;
The above is the detailed content of How do I add a primary key to a MySQL table and avoid common errors?. For more information, please follow other related articles on the PHP Chinese website!