约束字段为自动增长,被约束的字段必须同时被key约束
id自动增长,每插入一条记录,自动增长
创建一张表 t20 id 字段设置为 不为空 唯一 自动增长
mysql> create table t20(id int not null unique auto_increment,name varchar(16)); Query OK, 0 rows affected (0.01 sec) mysql> desc t20; +-------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(16) | YES | | NULL | | +-------+-------------+------+-----+---------+----------------+ 2 rows in set (0.00 sec)
只对name字段插入记录,我们看到id自动递增
mysql> insert into t20(name) values('mike'),('alex'),('ben'); Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from t20; +----+------+ | id | name | +----+------+ | 1 | mike | | 2 | alex | | 3 | ben | +----+------+ 3 rows in set (0.00 sec)
针对id,name 插入也可以的
#也可以指定id 从7开始
mysql> insert into t20(id,name) values(7,'apple'); Query OK, 1 row affected (0.00 sec) mysql> select * from t20; +----+-------+ | id | name | +----+-------+ | 1 | mike | | 2 | alex | | 3 | ben | | 7 | apple | +----+-------+
再针对name插入记录 id是从上次插入的记录开始计算
mysql> insert into t20(name) values('mike1'),('alex2'),('jack1'); Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from t20; +----+-------+ | id | name | +----+-------+ | 1 | mike | | 2 | alex | | 3 | ben | | 7 | apple | | 8 | mike1 | | 9 | alex2 | | 10 | jack1 | +----+-------+ 7 rows in set (0.00 sec)