简体   繁体   中英

alter table add foreign key fails

I have 3 tables and they all have innodb engine:

video(url, title, desc, country,...) url -> primary key
videoCat(_url, category) {_url,category} -> primary key
favorite(fav_url, thumb_path) fav_url -> primary key

then I do:

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

and everything goes smooth, but when I try:

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

I get:

1452 - Cannot add or update a child row: a foreign key constraint fails ( bascelik_lookaroundyou .<result 2 when explaining filename '#sql-efa_1a6e91a'>, CONSTRAINT #sql-efa_1a6e91a_ibfk_1 FOREIGN KEY ( _url ) REFERENCES video ( url ) ON DELETE CASCADE)

why???

ps I am using phpmyadmin ver. 3.3.9.2

The table videoCat has one or more rows that violates the foreign key constraint. This is usually that you have a row with a value for _url that does not exist in the table video.

You can check for this with the following query:

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

EDIT

Per request, here's a query to delete those pesky rows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM