[英]Error when adding foreign key
I had a table named movies
which had the fields id
as primary key, and two varchars: title
and genre
. 我有一个名为
movies
的表,其中的字段id
为主键,还有两个varchars: title
和genre
。
I created a new table named genres
with the int field id
as primary key and desription
varchar. 我创建了一个新的命名表
genres
与整型字段id
作为主键和desription
VARCHAR。 I changed the field genre
in my movies
table so I could create a foreign key referencing a genre. 我更改了
movies
表中的字段genre
,因此可以创建引用该类型的外键。
However, Mysql Workbench says there's an error when creating the foreign key. 但是,Mysql Workbench表示创建外键时出现错误。
Here's the statement: 声明如下:
ALTER TABLE `managemovies`.`movies`
ADD CONSTRAINT `genre_reference`
FOREIGN KEY (`genre` )
REFERENCES `managemovies`.`genres` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION
, ADD INDEX `genre_reference_idx` (`genero` ASC) ;
Error: 错误:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (`managemovies`.`#sql-3ba_2b`, CONSTRAINT `genre_reference` FOREIGN KEY (`genre`) REFERENCES `genres` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
SQL Statement: [... same statement than above ... ] ERROR: Error when running failback script. SQL语句:[...与上述语句相同...]错误:运行故障回复脚本时出错。 Details follow.
详细信息如下。
ERROR 1046: No database selected
SQL Statement:
CREATE TABLE `movies` [...]
[... the errors above repeated again ...]
clear your table contents and try adding foreign key. 清除表内容,然后尝试添加外键。
if your table contain data which not matching the foreign key field value you will see this error ... 如果您的表包含与外键字段值不匹配的数据,您将看到此错误...
It looks like your table movies
has data in genre column which is not present in genres.id column. 看起来您的桌
movies
在genre列中包含数据,而genres.id列中没有数据。
Your statement should work after removing the invalid data. 删除无效数据后,您的语句应起作用。
Hope it helps 希望能帮助到你
Vishad Vishad
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.