修改过一个比较糟糕的表设计,整个表没有主键,没有唯一字段,还存在存合同的大字段。
估计是上线时表结构已经定型,没有整合DBA的意见。但随着业务量的增长,原表的设计已经不能满足业务需求。所以开发又主动要求DBA配合修改表结构。
面对这样一张表,首先第一步,需要给表添加无意义自增主键。
给表添加int型主键ID
给已有的记录设置ID值:
因为这个表里面有大字段。以至于这个表非常大,因为服务器参数限制,修改报错。于是按记录分布情况分批操作:
+--------------------------------+----------+ | DATE_FORMAT(UPDATED_AT,‘%Y%m‘) | count(*) | +--------------------------------+----------+ | 201604 | 10 | | 201605 | 146 | | 201606 | 441 | | 201607 | 505 | | 201608 | 1317 | | 201609 | 14485 | | 201610 | 17110 | | 201611 | 35426 | | 201612 | 29740 | +--------------------------------+----------+ set @rownum = 0; UPDATE tt a SET a.ID = (@rownum:[email protected]+1) where DATE_FORMAT(UPDATED_AT,‘%Y%m‘)=‘201604‘; set @rownum = 100; UPDATE tt a SET a.ID = (@rownum:[email protected]+1) where DATE_FORMAT(UPDATED_AT,‘%Y%m‘)=‘201605‘; set @rownum = 300; UPDATE tt a SET a.ID = (@rownum:[email protected]+1) where DATE_FORMAT(UPDATED_AT,‘%Y%m‘)=‘201606‘; set @rownum = 1000; UPDATE tt a SET a.ID = (@rownum:[email protected]+1) where DATE_FORMAT(UPDATED_AT,‘%Y%m‘)=‘201607‘; set @rownum = 1600; UPDATE tt a SET a.ID = (@rownum:[email protected]+1) where DATE_FORMAT(UPDATED_AT,‘%Y%m‘)=‘201608‘; set @rownum = 3000; UPDATE tt a SET a.ID = (@rownum:[email protected]+1) where DATE_FORMAT(UPDATED_AT,‘%Y%m‘)=‘201609‘; set @rownum = 20000; UPDATE tt a SET a.ID = (@rownum:[email protected]+1) where DATE_FORMAT(UPDATED_AT,‘%Y%m‘)=‘201610‘; set @rownum = 40000; UPDATE tt a SET a.ID = (@rownum:[email protected]+1) where DATE_FORMAT(UPDATED_AT,‘%Y%m‘)=‘201611‘; set @rownum = 80000; UPDATE tt a SET a.ID = (@rownum:[email protected]+1) where DATE_FORMAT(UPDATED_AT,‘%Y%m‘)=‘201612‘; SELECT COUNT(*) FROM tt a WHERE a.ID IS NULL; 0 SELECT a.ID,COUNT(*) FROM tt a GROUP BY a.ID HAVING COUNT(*)>1; 0 select id,updated_at from tt where id in( SELECT a.ID FROM tt a GROUP BY a.ID HAVING COUNT(*)>1); set @rownum = 110000; UPDATE tt a SET a.ID = (@rownum:[email protected]+1) where a.ID IS NULL; ALTER TABLE tt MODIFY COLUMN ID bigint(20) NOT NULL PRIMARY KEY AUTO_INCREMENT COMMENT ‘主键‘;ALTER TABLE tt AUTO_INCREMENT=120000;
感悟就是 :
1、关于大字段,要么存成文件的形式,要么单独存一张表,不要和其它字段和在一起。这样的话会导致任何对该表的操作都会牵一发而动全身。
2、表一定要有主键;
时间: 2024-10-11 07:43:21