简体   繁体   中英

Mysql Issue Related to foreign key and on delete cascade

I have 4 sql tables.

create table general(regno int NOT NULL primary key);

create table company_information(cregno int NOT NULL primary key);

create table company_jobs (jcode int NOT NULL primary key, cregno int , foreign key(cregno) references company_information(cregno));

create table applied(cregno int ,jcode int, regno int, foreign key(regno) references general(regno), foreign key(jcode) references company_jobs(jcode));

All i need to do is delete from table company_jobs when table applied has some value. Actually, all the tables must have some value for table applied to have some value as you can see from the structure of tables. I used these commands to add ON DELETE CASCADE Constraint:

alter table company_jobs add constraint fk_cregno13 foreign key(cregno) references company_information (cregno) on delete cascade;

alter table applied add constraint fk_jcode16 foreign key(jcode) references company_jobs(jcode) on delete cascade;

alter table applied add constraint fk_regno14 foreign key(regno) references general(regno) on delete cascade;

But it is not working unfortunately and i am getting this error when i am giving the following command.

mysql> delete from company_jobs;

ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constrai nt fails ( test . applied , CONSTRAINT applied_ibfk_2 FOREIGN KEY ( jcode ) RE FERENCES company_jobs ( jcode ))

Help me out please if anyone can. Thank you

The 1st foreign key pointing from table applied to company_job doesn't have any cascade rule, so it simple blocks the delete from company_job;

See mysql dump bellow

ALTER TABLE `applied`
  ADD CONSTRAINT `applied_ibfk_1` FOREIGN KEY (`regno`) REFERENCES `general` (`regno`),
  ADD CONSTRAINT `applied_ibfk_2` FOREIGN KEY (`jcode`) REFERENCES `company_jobs` (`jcode`),
  ADD CONSTRAINT `fk_jcode16` FOREIGN KEY (`jcode`) REFERENCES `company_jobs` (`jcode`) ON DELETE CASCADE,
  ADD CONSTRAINT `fk_regno14` FOREIGN KEY (`regno`) REFERENCES `general` (`regno`) ON DELETE CASCADE;

You need to drop the foreign key first, or recreate the table without the 1st foreign key

ALTER TABLE 'applied' DROP CONTRAINT 'applied_ibfk_2';

When you created the applied table you created 2 foreign keys.

After that, you have added 2 other foreign keys to this table.

As you can see, the error references a foreign key named applied_ibfk_2 that's not the foreign key you added after the creation.

Thus, ad the moment you have 4 foreign key constraint on that table.

So, you have to drop the 2 foreign keys created on table creation (that have a predefined name) and everything will work

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