How to update foreign key value in mysql database

萝らか妹 提交于 2019-11-28 19:21:21

问题


I have three tables: categories, languages and categories_languages. Categories_languages is many to many table which links together categories and languages. I would like to update a foregin key value in table languages but it throws me error #1451 - Cannot delete or update a parent row: a foreign key constraint fails!

CREATE TABLE IF NOT EXISTS `categories` (
  `id` int(11) unsigned NOT NULL auto_increment,
  `name` varchar(20) NOT NULL,
  `modified` int(10) unsigned NOT NULL,
  PRIMARY KEY  (`id`),
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `languages` (
  `id` char(2) NOT NULL,
  `name` varchar(20) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `categories_languages` (
  `id` int(11) unsigned NOT NULL auto_increment,
  `category_id` int(11) unsigned NOT NULL,
  `language_id` char(2) NOT NULL,
  `translation` varchar(20) NOT NULL,
  PRIMARY KEY  (`id`),
  KEY `fk_category_id_language_id` (`category_id`,`language_id`),
  KEY `fk_language_id` (`language_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 ;

ALTER TABLE `categories_languages`
  ADD CONSTRAINT `categories_languages_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `categories_languages_ibfk_2` FOREIGN KEY (`language_id`) REFERENCES `languages` (`id`) ON DELETE CASCADE;

The error is clear to me, but how can I update a key value in this case? I tried adding ON UPDATA CASCADE:

ALTER TABLE `categories_languages`
  ADD CONSTRAINT `categories_languages_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `categories_languages_ibfk_2` FOREIGN KEY (`language_id`) REFERENCES `languages` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

but that also fails with message: MySQL said: Documentation #1005 - Can't create table './db_dodo/#sql-c2f_80e6f.frm' (errno: 121)


回答1:


You can temporarily suspend foreign key checking:

SET foreign_key_checks = 0;
UPDATE languages SET id='xyz' WHERE id='abc';
UPDATE categories_languages SET language_id='xyz' WHERE language_id='abc';
SET foreign_key_checks = 1;

EDIT: As for the foreign key problem: is the data stored on a local or a remote file system? errno 121 is EREMOTEIO (Remote I/O error). Perhaps there are permission problems on the target file system or it doesn't support the # character in filenames?




回答2:


If you are looking for a temp solution you can also change the ON UPDATE action to CASCADE and modify your ids



来源:https://stackoverflow.com/questions/7541446/how-to-update-foreign-key-value-in-mysql-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!