MySQL数据库为什么习惯用自增序列作为主键

对于这个问题需要从MySQL的索引以及存储引擎谈起:

InnoDB的primary key为cluster index,除此之外,不能通过其他方式指定cluster index,如果InnoDB不指定primary key,InnoDB会找一个unique not null的field做cluster index,如果还没有这样的字段,则InnoDB会建一个非可见的系统默认的主键---row_id(6个字节长)作为cluster_index。

建议使用数字型auto_increment的字段作为cluster index。不推荐用字符串字段做cluster index (primary key) ,因为字符串往往都较长, 会导致secondary index过大(secondary index的叶子节点存储了primary key的值),而且字符串往往是乱序。cluster index乱序插入容易造成插入和查询的效率低下。

以上就是为什么最好用自增长序列作为主键的原因。

猜你喜欢

转载自blog.csdn.net/weixin_42330675/article/details/81287274