I’ve been hinted into giving foreign keys a go as I’m trying to get better at database programming. The problem was, if a job in the jobs table was deleted, it left orphan messages relating to it in the messages table. So foreign keys were introduced to me to be the solution.
However, I’ve gotten this when trying to do it, and I’m not sure what it’s saying, plus, I’m not even sure which way round I should be setting the restriction, from the job to the messages, or vice versa. 🙁
Here’s the error:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`nzua9c8_tasks`.<result 2 when explaining filename '#sql-2929_701930'>, CONSTRAINT `#sql-2929_701930_ibfk_1` FOREIGN KEY (`id`) REFERENCES `jobs` (`id`) ON UPDATE NO ACTION)
Also, the interface for PHPMyAdmin suggested that when I delete a task, the message ID would be “restricted”. I didn’t have an option for delete. I want any messages with a “job_id” that matches an id in the jobs table to be deleted too.
Thanks for any help offered.
You want to add
on delete cascadeto your foreign key definition (just afteron update no actionin your script).So it would be something like:
More can be found here.