数据库
首页 > 数据库> > MySQL错误1452-无法添加或更新子行:外键约束失败

MySQL错误1452-无法添加或更新子行:外键约束失败

作者:互联网

我已经看过其他人关于此主题的问题,但似乎找不到我的错误出处.任何帮助将不胜感激.我包括了我能想到的尽可能多的东西,这可能有助于发现问题:

CREATE TABLE stocks (
id INT AUTO_INCREMENT NOT NULL,
user_id INT(11) UNSIGNED NOT NULL,
ticker VARCHAR(20) NOT NULL,
name VARCHAR(20),
rating INT(11),
position ENUM("strong buy", "buy", "sell", "strong sell", "neutral"),
next_look DATE,
privacy ENUM("public", "private"),
PRIMARY KEY(id),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
 ENGINE=InnoDB DEFAULT CHARSET=utf8;



CREATE TABLE IF NOT EXISTS `stocks_tags` (
  `stock_id` INT NOT NULL,
  `tag_id` INT NOT NULL,
  PRIMARY KEY  (`stock_id`,`tag_id`),
  KEY `fk_stock_tag` (`tag_id`),
  KEY `fk_tag_stock` (`stock_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `stocks_tags`
  ADD CONSTRAINT `fk_stock_tag` FOREIGN KEY (`tag_id`) REFERENCES `tags` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `fk_tag_stock` FOREIGN KEY (`stock_id`) REFERENCES `stocks` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;



CREATE TABLE tags(
id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
tags VARCHAR(30),
UNIQUE(tags)
)
ENGINE=INNODB DEFAULT CHARSET=utf8;

我得到的错误是:

Database_Exception [ 1452 ]: Cannot add or update a child row: a foreign key constraint 
fails (`ddmachine`.`stocks_tags`, CONSTRAINT `fk_stock_tag` FOREIGN KEY (`tag_id`) REFERENCES  
`tags` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) [ INSERT INTO `stocks_tags` (`stock_id`, 
`tag_id`) VALUES (19, 'cash') ]

我确实看到其他人根据其枚举列也遇到了类似的问题,但事实并非如此.

解决方法:

这意味着标签表中缺少tag_id现金… tag_id不应为整数吗?

(在此查询中,我的意思是)

INSERT INTO `stocks_tags` (`stock_id`, `tag_id`) VALUES (19, 'cash')

标签:foreign-keys,mysql,database
来源: https://codeday.me/bug/20191106/2000267.html