问题
I have a table with 38.000 records, but without any auto increment column like ID
.
Now I have to add an ID
column, and I'm wondering could there be troubles?
回答1:
You problem with definition change to any field is the change is "destructive". It is best to treat changes like this as a data migration. I have not done this with MySQL, but have had to add auto numbering to SQL Server. The basic idea is the same.
Check the documentation, as MySQL may have a mechanism for adding aut increment without resetting the field. If so, doing it via SQL will solve the problem. In general, I recommend against doing these types of changes visually, with a tool, as most tools are very destructive in their methdology.
回答2:
You can add do that without problem only if your table doesn't have relationship with others.
You must remove the old primary key and upload the table accordingly (perhaps add an unique index on the old primary key).
Proceed like that :
Make a dump of your database
Remove the primary key like that
ALTER TABLE XXX DROP PRIMARY KEY
- Add the new column like that
ALTER TABLE XXX add column Id INT NOT NULL AUTO_INCREMENT FIRST, ADD primary KEY Id(Id)
The table will be looked and the AutoInc updated.
回答3:
This will add an auto increment ID to your MySQL table:
ALTER TABLE `your_table_name` ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;
Depending on the amount of data on your table it could take a few minutes to complete.
回答4:
This is the solution that i tried with MySQL Workbench:
ALTER TABLE `tableName` CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT ;
I don't know if this is correct way, but I didn't notice any problem in my Java EE Application yet.
回答5:
I work with very large data and had an id column filled with NULLS. I chose to run the following SQL to fill with numbers... then I set the id column to be my primary key.
set @row = 0;
UPDATE philadelphia.msg_geo_sal SET id = @row := @row + 1;
回答6:
"could there be troubles?"
There could be troubles just inserting a record. However...
Generally, adding a new field usually is pretty safe to do, whether it's an auto-incrementing column or not. It's changing or deleting columns that are the most likely to cause you issues if you're not sure of all the dependencies.
To be safe, however, I'd try it on a copy (test) version first and run your app(s) against the test version first, just to be safe. It's good practice to use a test environment no matter what anyway.
Can you be more specific about what types of troubles you're worried about?
回答7:
You may need to add it as primary key first before you can make it as auto increase field
You can look at this example
ALTER TABLE `category`
ADD PRIMARY KEY (`cat_id`);
ALTER TABLE `category`
MODIFY `cat_id` int(11) NOT NULL AUTO_INCREMENT;
来源:https://stackoverflow.com/questions/4829400/troubles-of-adding-a-new-id-auto-increment-after-table-exist