alter table add外键失败

时间:2011-05-05 20:22:54

标签: mysql

我有3张桌子,他们都有innodb引擎:

video(url, title, desc, country,...) url -> primary key
videoCat(_url, category) {_url,category} -> primary key
favorite(fav_url, thumb_path) fav_url -> primary key
然后我做了:

alter table favorite
add foreign key(fav_url) references video(url)
on delete cascade

一切顺利,但是当我尝试时:

alter table videoCat
add foreign key(_url) references video(url)
on delete cascade

我明白了:

  

1452 - 无法添加或更新子行:外键约束失败(bascelik_lookaroundyou。<结果2解释文件名'#sql-efa_1a6e91a'>,CONSTRAINT #sql-efa_1a6e91a_ibfk_1 FOREIGN KEY( _url)参考videourl)ON DELETE CASCADE)

为什么???

P.S。我正在使用phpmyadmin ver。 3.3.9.2

1 个答案:

答案 0 :(得分:35)

表videoCat有一行或多行违反外键约束。通常情况下,您有一个_url值的行在表视频中不存在。

您可以使用以下查询进行检查:

SELECT videoCat._url
FROM videoCat LEFT JOIN video ON videoCat._url = video.url
WHERE video.url IS NULL

修改

根据请求,这是一个删除那些讨厌的行的查询:

DELETE FROM videoCat
WHERE NOT EXISTS (
    SELECT *
    FROM video
    WHERE url = videoCat._url
)