Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to properly handle update/delete operations in a RDBMS?
    primarykey
    data
    text
    <p>I recently designed my first relational database in MySQL, using InnoDB as the engine for all of my tables. I would like to know how to properly handle <code>DELETE</code> and <code>UPDATE</code> operations when you have many-to-one relationships.</p> <p><strong>Example</strong></p> <p>Let's say you have the following tables:</p> <p><strong>t1</strong><br> PK&nbsp;&nbsp;&nbsp;&nbsp;t1_ID<br> FK&nbsp;&nbsp;&nbsp;&nbsp;t2_ID<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;A</p> <p><strong>t2</strong><br> PK&nbsp;&nbsp;&nbsp;&nbsp;t2_ID<br> FK&nbsp;&nbsp;&nbsp;&nbsp;t3_ID<br> FK&nbsp;&nbsp;&nbsp;&nbsp;t4_ID</p> <p><strong>t3</strong><br> PK&nbsp;&nbsp;&nbsp;&nbsp;t3_ID<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;B</p> <p><strong>t4</strong><br> PK&nbsp;&nbsp;&nbsp;&nbsp;t4_ID<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;C</p> <p>With those tables, a cascade on delete operation is specified for the FK in <code>t1</code> and for both FKs in <code>t2</code>. If one or more records are deleted from <code>t3</code> or <code>t4</code> the corresponding records in <code>t2</code> and <code>t1</code> are also deleted.</p> <p><strong>Questions</strong></p> <p>The delete functionality that I need is the reverse. I want the following to occur:</p> <ol> <li>Delete a record in <code>t1</code></li> <li>Delete the corresponding record in <code>t2</code></li> <li>If the corresponding record in <code>t3</code> is not used anywhere else, i.e. that <code>t3_ID</code> is not anywhere else in <code>t2</code>, delete the corresponding record in <code>t3</code></li> <li>Repeat step 3 for <code>t4</code></li> </ol> <p>I also need a similar functionality for the update operations.</p> <ol> <li>If the record in <code>t3</code>/<code>t4</code> has no other entries in <code>t2</code>, then the value can simply be changed.</li> <li>If the record in <code>t3</code>/<code>t4</code> is in at least one other record in t2, a new record will need to be created in <code>t3</code>/<code>t4</code> and the reference in <code>t2</code> will need to be updated.</li> </ol> <p>How can I achieve this?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload