auto_incrment 属性用于为新行生成唯一标识。如果列被声明为“not null”,则可以将 null 分配给该列以生成数字序列。
当将任何值插入到 auto_increment 列中时,该列将被设置为该列值,并且序列也会被重置,以便它在最大列值的顺序范围内自动生成值。
可以更新现有的“auto_incrment”列,这也会重置“auto_incrment”序列。最新自动生成的‘auto_incrment;可以使用 sql 中的“last_insert_id()”函数或使用 c api 函数“mysql_insert_id()”来检索值。
这些函数是特定于连接的,这意味着它们的返回值不是受执行插入操作的其他连接的影响。可以使用“auto_incrment”列的最小整数数据类型,该数据类型足够大以容纳用户所需的最大序列值。
auto_increment 规则使用 auto_incrment 属性时需要遵循以下规则 -
每个表只有一个 auto_incrment 列,其数据类型为通常为整数。
auto_increment 列需要建立索引。这意味着它可以是primary key 或 unique 索引。
auto_incrment 列必须具有 not null 约束。
当 auto_increment 时属性设置为列,mysql自动添加对列本身的 not null 约束。
如果 id 列尚未添加到表中,则可以使用以下语句 -
alter table tablename add id int unsigned not null auto_increment, add index (id);
如果 id 列已经存在,则可以使用以下命令 -
alter table tablename auto_increment=specificvalue;
这里,tablename是指需要设置“auto_incrment”列的表的名称。 “specificvalue”是指用户指定“auto_incrment”值开始的整数。
以上就是mysql中如何设置初始值和自增?的详细内容。
