最近修改MySQL数据库表中的字段长度时报错,执行更改的sql语句:ALTER TABLE server_list MODIFY COLUMN server_lip CHAR(25);
报错信息: 1 queries executed, 0 success, 1 errors, 0 warnings 查询:alter table server_list modify column server_lip char(25) 错误代码: 1833 Cannot change column 'server_lip': used in a foreign key constraint 'server_history_ibfk_1' of table 'OMServer.server_history'
原因:server_list表中的server_lip字段为server_history表的外键,server_history建表语句:
CREATE TABLE server_history
(
ID
int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
history_id
int(11) NOT NULL COMMENT '事件ID',
history_ip
char(15) NOT NULL COMMENT '事件IP地址',
history_user
char(15) NOT NULL COMMENT '事件用户名',
history_datetime
datetime NOT NULL COMMENT '事件时间',
db_datetime
timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '入库时间',
history_command
char(255) NOT NULL COMMENT '事件命令',
PRIMARY KEY (ID
),
KEY history_ip
(history_ip
),
CONSTRAINT server_history_ibfk_1
FOREIGN KEY (history_ip
) REFERENCES server_list
(server_lip
)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8 COMMENT='操作事件表'
解决步骤: 1.锁表 LOCK TABLES server_history WRITE,server_list WRITE; 2.查看是否被锁
3.解除server_history表外键约束 ALTER TABLE server_history DROP FOREIGN KEY server_history_ibfk_1; 4.更改server_list表server_lip字段长度 ALTER TABLE server_list MODIFY COLUMN server_lip CHAR(25); 查看表结构发现已完成字段长度更新
5.新增server_history表外键约束
ALTER TABLE server_history
ADD CONSTRAINT server_history_ibfk_1
FOREIGN KEY (history_ip
) REFERENCES server_list
(server_lip
);
6.解除锁定 UNLOCK TABLES;