我有以下2个表格:
CREATE TABLE `personal_info` (
`p_id` int(11) NOT NULL AUTO_INCREMENT,
`name` text NOT NULL,
`initials` text NOT NULL,
`surname` text NOT NULL,
`home_lang` int(11) NOT NULL,
PRIMARY KEY (`p_id`),
KEY `home_lang` (`home_lang`),
CONSTRAINT `personal_info_ibfk_1` FOREIGN KEY (`home_lang`) REFERENCES `language_list` (`ll_id`)
) ENGINE=InnoDB AUTO_INCREMENT=44 DEFAULT CHARSET=latin1
CREATE TABLE `language_list` (
`ll_id` int(11) NOT NULL AUTO_INCREMENT,
`name` text NOT NULL,
PRIMARY KEY (`ll_id`)
) ENGINE=InnoDB AUTO_INCREMENT=73 DEFAULT CHARSET=latin1
我正在尝试使用以下内容从表中删除列:
ALTER TABLE `personal_info` DROP `home_lang`
但是因为我收到这个错误所以不能这样做:
#1025 - Error on rename of '.\MyDB\#sql-112c_82' to '.\MyDB\personal_info' (errno: 150)
我尝试先删除索引,然后删除列:
ALTER TABLE personal_info DROP INDEX home_lang
但后来我收到以下错误:
#1553 - Cannot drop index 'home_lang': needed in a foreign key constraint
所以我试图删除外键:
ALTER TABLE personal_info DROP FOREIGN KEY home_lang
但是收到了这个错误:
#1025 - Error on rename of '.\MyDB\personal_info' to '.\MyDB\#sql2-112c-8d' (errno: 152)
我还尝试先将所有值设置为null:
update personal_info set home_lang = null
但后来收到了这个错误:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`MyDB`.`personal_info`, CONSTRAINT `personal_info_ibfk_1` FOREIGN KEY (`home_lang`) REFERENCES `language_list` (`ll_id`))
现在我被卡住了。我尝试过一些东西但是无法删除列。除了删除列之外,我不允许以任何方式更改数据库。
答案 0 :(得分:22)
您的DROP FOREIGN KEY
语法使用了错误的密钥名称。它试图在home_lang
字段上删除“普通”索引。这不是外键本身。
CONSTRAINT `personal_info_ibfk_1` FOREIGN KEY (`home_lang`) REFERENCES `language_list` (`ll_id`)
^^^^^^^^^^^^^^^^^^^^^--- THIS is the name of the foreign key
尝试:
ALTER TABLE personal_info DROP FOREIGN KEY `personal_info_ibfk_1`
答案 1 :(得分:1)
使用下面给出的查询查询外键的名称。
SHOW CREATE TABLE forms_main;
然后,一旦您获得了密钥,就执行放置外键命令
alter TABLE `forms_main`
drop FOREIGN key `forms_main_ibfk_1`;
然后执行放置列命令
ALTER TABLE `forms_main` DROP `company_id`;
答案 2 :(得分:0)
更改表db_name
。table_name
删除外键foreign_key
;
更改表test
。exam
DROP INDEX id
;