共计 1317 个字符,预计需要花费 4 分钟才能阅读完成。
最近修改 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;