如何用 MySQL 中自动生成值的新列替换主键?
How to replace primary key with new column with autogenerated values in MySQL?
我有一个 table merchants
和下一列:name, program_id, program_name
。
当前主键是name + program_id
我需要做的是添加一个新列 id
,用自动生成的值(最好是 uuid 或类似的东西)填充它并使其成为一个新的主键。
怎么做?
ALTER table merchants DROP PRIMARY KEY, ADD id INT NOT NULL AUTO_INCREMENT PRIMARY KEY;
如果你的数据库引擎是innodb,我建议你使用自增整数作为主键,而不是uuid,因为innodb中的主键是集群的index.Auto自增主键可以减少分页
Notice that not only does it take longer to insert the rows with the UUID primary key,but the resulting indexes are quite a bit bigger. Some of that is due to the larger primary key, but some of it is undoubtedly due to page splits and resultant fragmentation as well.
以及使用顺序主键的缺点:
- 目标页面可能已经刷新到磁盘并从缓存中删除,或者可能从未放入缓存中,在这种情况下,InnoDB 必须找到它并在插入之前从磁盘中读取它新行。这会导致很多随机 I/O.
- 当插入顺序不正确时,InnoDB 必须频繁拆分页面以为新行腾出空间。这需要移动大量数据,并且修改至少三页而不是一页。
- 由于拆分,页面变得稀疏且不规则填充,因此最终数据是碎片化的。
如果您想了解更多关于主键对页面拆分或页面合并的影响,可以访问here
我有一个 table merchants
和下一列:name, program_id, program_name
。
当前主键是name + program_id
我需要做的是添加一个新列 id
,用自动生成的值(最好是 uuid 或类似的东西)填充它并使其成为一个新的主键。
怎么做?
ALTER table merchants DROP PRIMARY KEY, ADD id INT NOT NULL AUTO_INCREMENT PRIMARY KEY;
如果你的数据库引擎是innodb,我建议你使用自增整数作为主键,而不是uuid,因为innodb中的主键是集群的index.Auto自增主键可以减少分页
Notice that not only does it take longer to insert the rows with the UUID primary key,but the resulting indexes are quite a bit bigger. Some of that is due to the larger primary key, but some of it is undoubtedly due to page splits and resultant fragmentation as well.
以及使用顺序主键的缺点:
- 目标页面可能已经刷新到磁盘并从缓存中删除,或者可能从未放入缓存中,在这种情况下,InnoDB 必须找到它并在插入之前从磁盘中读取它新行。这会导致很多随机 I/O.
- 当插入顺序不正确时,InnoDB 必须频繁拆分页面以为新行腾出空间。这需要移动大量数据,并且修改至少三页而不是一页。
- 由于拆分,页面变得稀疏且不规则填充,因此最终数据是碎片化的。
如果您想了解更多关于主键对页面拆分或页面合并的影响,可以访问here