3.6.9 Using 使用AUTO_INCREMENT

The AUTO_INCREMENT attribute can be used to generate a unique identity for new rows:AUTO_INCREMENT属性可用于为新行生成唯一标识:

CREATE TABLE animals (
     id MEDIUMINT NOT NULL AUTO_INCREMENT,
     name CHAR(30) NOT NULL,
     PRIMARY KEY (id)
);

INSERT INTO animals (name) VALUES
    ('dog'),('cat'),('penguin'),
    ('lax'),('whale'),('ostrich');

SELECT * FROM animals;

Which returns:返回:

+----+---------+
| id | name    |
+----+---------+
|  1 | dog     |
|  2 | cat     |
|  3 | penguin |
|  4 | lax     |
|  5 | whale   |
|  6 | ostrich |
+----+---------+

No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. 没有为AUTO_INCREMENT列指定任何值,因此MySQL会自动分配序列号。You can also explicitly assign 0 to the column to generate sequence numbers, unless the NO_AUTO_VALUE_ON_ZERO SQL mode is enabled. 除非启用了NO_AUTO_VALUE_ON_ZERO SQL模式,否则也可以将0显式分配给列以生成序列号。For example:例如

INSERT INTO animals (id,name) VALUES(0,'groundhog');

If the column is declared NOT NULL, it is also possible to assign NULL to the column to generate sequence numbers. For example:如果列被声明为NOT NULL,也可以将NULL分配给列以生成序列号。例如

INSERT INTO animals (id,name) VALUES(NULL,'squirrel');

When you insert any other value into an AUTO_INCREMENT column, the column is set to that value and the sequence is reset so that the next automatically generated value follows sequentially from the largest column value. For example:AUTO_INCREMENT列中插入任何其他值时,该列将被设置为该值,并且序列将被重置,以便下一个自动生成的值从最大列值开始依次出现。例如

INSERT INTO animals (id,name) VALUES(100,'rabbit');
INSERT INTO animals (id,name) VALUES(NULL,'mouse');
SELECT * FROM animals;
+-----+-----------+
| id  | name      |
+-----+-----------+
|   1 | dog       |
|   2 | cat       |
|   3 | penguin   |
|   4 | lax       |
|   5 | whale     |
|   6 | ostrich   |
|   7 | groundhog |
|   8 | squirrel  |
| 100 | rabbit    |
| 101 | mouse     |
+-----+-----------+

Updating an existing AUTO_INCREMENT column value also resets the AUTO_INCREMENT sequence.更新现有的AUTO_INCREMENT列值也会重置AUTO_INCREMENT序列。

You can retrieve the most recent automatically generated AUTO_INCREMENT value with the LAST_INSERT_ID() SQL function or the mysql_insert_id() C API function. These functions are connection-specific, so their return values are not affected by another connection which is also performing inserts.您可以使用LAST_INSERT_ID()SQL函数或mysql_insert_id()C API函数检索最新自动生成的AUTO_INCREMENT值。这些函数是特定于连接的,因此它们的返回值不受同时执行插入的另一个连接的影响。

Use the smallest integer data type for the AUTO_INCREMENT column that is large enough to hold the maximum sequence value you require. AUTO_INCREMENT列使用最小的整数数据类型,该数据类型足够大,可以容纳所需的最大序列值。When the column reaches the upper limit of the data type, the next attempt to generate a sequence number fails. 当列达到数据类型的上限时,下一次尝试生成序列号失败。Use the UNSIGNED attribute if possible to allow a greater range. For example, if you use TINYINT, the maximum permissible sequence number is 127. 如果可能,请使用UNSIGNED属性以允许更大的范围。例如,如果使用TINYINT,则允许的最大序列号为127。For TINYINT UNSIGNED, the maximum is 255. 对于TINYINT UNSIGNED,最大值为255。See Section 11.1.2, “Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT” for the ranges of all the integer types.有关所有整数类型的范围,请参阅第11.1.2节,“整数类型(精确值)-Integer、INT、SMALLINT、TINYINT、MEDIUMINT、BIGINT”

Note注意

For a multiple-row insert, LAST_INSERT_ID() and mysql_insert_id() actually return the AUTO_INCREMENT key from the first of the inserted rows. 对于多行插入,LAST_insert_ID()mysql_insert_ID()实际上从插入的第一行返回AUTO_INCREMENT键。This enables multiple-row inserts to be reproduced correctly on other servers in a replication setup.这使多行插入能够在复制设置中的其他服务器上正确复制。

To start with an AUTO_INCREMENT value other than 1, set that value with CREATE TABLE or ALTER TABLE, like this:要从AUTO_INCREMENT值而不是1开始,请使用CREATE TABLEALTER TABLE设置该值,如下所示:

mysql> ALTER TABLE tbl AUTO_INCREMENT = 100;

InnoDB Notes

For information about AUTO_INCREMENT usage specific to InnoDB, see Section 15.6.1.6, “AUTO_INCREMENT Handling in InnoDB”.有关InnoDB特定的AUTO_INCREMENT使用的信息,请参阅第15.6.1.6节,“InnoDB中的AUTO_INCREMENT处理”

MyISAM Notes

  • For MyISAM tables, you can specify AUTO_INCREMENT on a secondary column in a multiple-column index. 对于MyISAM表,可以在多列索引的辅助列上指定AUTO_INCREMENTIn this case, the generated value for the AUTO_INCREMENT column is calculated as MAX(auto_increment_column) + 1 WHERE prefix=given-prefix. 在这种情况下,AUTO_INCREMENT列的生成值计算为MAX(AUTO_INCREMENT_column)+1其中前缀=given-prefixThis is useful when you want to put data into ordered groups.当您想将数据放入有序的组中时,这很有用。

    CREATE TABLE animals (
        grp ENUM('fish','mammal','bird') NOT NULL,
        id MEDIUMINT NOT NULL AUTO_INCREMENT,
        name CHAR(30) NOT NULL,
        PRIMARY KEY (grp,id)
    ) ENGINE=MyISAM;
    
    INSERT INTO animals (grp,name) VALUES
        ('mammal','dog'),('mammal','cat'),
        ('bird','penguin'),('fish','lax'),('mammal','whale'),
        ('bird','ostrich');
    
    SELECT * FROM animals ORDER BY grp,id;

    Which returns:返回:

    +--------+----+---------+
    | grp    | id | name    |
    +--------+----+---------+
    | fish   |  1 | lax     |
    | mammal |  1 | dog     |
    | mammal |  2 | cat     |
    | mammal |  3 | whale   |
    | bird   |  1 | penguin |
    | bird   |  2 | ostrich |
    +--------+----+---------+

    In this case (when the AUTO_INCREMENT column is part of a multiple-column index), AUTO_INCREMENT values are reused if you delete the row with the biggest AUTO_INCREMENT value in any group. 在这种情况下(当AUTO_INCREMENT列是多列索引的一部分时),如果删除任何组中AUTO_INCREMENT值最大的行,则会重用AUTO_INCREENT值。This happens even for MyISAM tables, for which AUTO_INCREMENT values normally are not reused.即使对于MyISAM表也会发生这种情况,因为AUTO_INCREMENT值通常不会被重用。

  • If the AUTO_INCREMENT column is part of multiple indexes, MySQL generates sequence values using the index that begins with the AUTO_INCREMENT column, if there is one. 如果AUTO_INCREMENT列是多个索引的一部分,MySQL将使用以AUTO_INCREMENT列开头的索引(如果有)生成序列值。For example, if the animals table contained indexes PRIMARY KEY (grp, id) and INDEX (id), MySQL would ignore the PRIMARY KEY for generating sequence values. 例如,如果animals表包含索引PRIMARY KEY (grp, id)INDEX (id),MySQL将忽略PRIMARY KEY以生成序列值。As a result, the table would contain a single sequence, not a sequence per grp value.因此,该表将包含单个序列,而不是每个grp值的序列。

Further Reading进一步阅读

More information about AUTO_INCREMENT is available here:有关AUTO_INCREMENT的更多信息,请点击此处: