1

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?
Salitha
  • 111
  • 4
  • 2
    The proper way is to create the foreing key constraint with the ON UPDATE CASCADE option: https://dba.stackexchange.com/questions/74627/difference-between-on-delete-cascade-on-update-cascade-in-mysql – Andrea B. Jun 27 '23 at 09:19
  • modify to parent_id=101 -- Are you running an adoption agency? Seriously, there is virtually no database need to modify a PRIMARY KEY. – Rick James Jun 27 '23 at 22:53
  • Does your code fail without the SETs? (And didn't you mean 1 for the final SET?) – Rick James Jun 27 '23 at 22:55
  • @RickJames yes, I meant 1, 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:05
  • (I'm not a fan of FKs; there are so many situations where users stumble over the limitations and tricky things. As for CASCADE, I prefer to write code to do such instead of it silently happening.) – Rick James Jun 29 '23 at 16:24

0 Answers0