P粉3916779212023-08-23 15:36:57
I also encountered this problem when I tried to convert a column to auto_increment, and one of the rows had a value of 0. An alternative is by setting:
SET SESSION sql_mode='NO_AUTO_VALUE_ON_ZERO';
to set up the session.
This changes the column to an auto_increment with a zero ID.
Zero is not ideal, nor do I recommend using it in auto_increment columns. Unfortunately, it's part of the inherited dataset, so I can't change it for now.
It's best to clear the settings (and other settings) afterward:
SET SESSION sql_mode='';
Although it will be cleared when the current client session is closed.
Full details about the 'NO_AUTO_VALUE_ON_ZERO' setting here.
P粉1460805562023-08-23 00:06:11
This happens if the table contains an existing record with an id of 0 (or a negative number). Updating all existing records to use positive values will allow auto_increment to be set on that column.
Edit: Some people asked how 0 appeared. To clarify, the MySQL Reference Manual states, "For numeric types, the default value is 0, but for integer or floating-point types with the AUTO_INCREMENT attribute, the default value is the next value in the sequence." So if you do this before enabling auto_increment in When performing an insert on a table without providing a value for a numeric column, the default value of 0 is used during the insert. More details can be found at https://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html.