Consider following relationship on MySQL database.
+--------------+ +---------------+
| Child | | Parent |
+--------------+ 1 +---------------+
| child_id (PK)| 1 |-----| parent_id (PK)|
| parent_id(FK)|-------------| | name |
| name | | address |
| age | +---------------+
| gender |
| grade |
+--------------+
I want to update a record where parent_id = 100. My requirement is to modify to parent_id=101. Assume there is no records as 101. This operation need to update child.parent_id = 101 as well so the original relation remains.
My current approach is, roughly
START TRANSACTION;
SET FOREIGN_KEY_CHECKS = 0;
UPDATE Child SET parent_id=101 WHERE parent_id=100;
UPDATE Parent SET parent_id=101 WHERE parent_id=100;
SET FOREIGN_KEY_CHECKS = 1;
COMMIT;
- Can this be problematic in production environment where thousands of writes per second done?
- Is there a proper way I can achieve this without disabling foreign key checks?
modify to parent_id=101-- Are you running an adoption agency? Seriously, there is virtually no database need to modify aPRIMARY KEY. – Rick James Jun 27 '23 at 22:53SETs? (And didn't you mean1for the finalSET?) – Rick James Jun 27 '23 at 22:551, sorry for typo. Yah, I want to run adoption agency in a legal way. Jokes aside, this is just an abstraction of a scenario happened to me few days ago. I was trying to perform a soft delete then add another record (child and parent) with same primary keys. I wondered if I ever happened to perform such thing on a production environment (hypothetically) what are my options to do it safely. This is the explanation, but this question is purely out of curiosity. – Salitha Jun 29 '23 at 05:05CASCADE, I prefer to write code to do such instead of it silently happening.) – Rick James Jun 29 '23 at 16:24