Question

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 DELETE and UPDATE operations when you have many-to-one relationships.

Example

Let's say you have the following tables:

t1
PK    t1_ID
FK    t2_ID
        A

t2
PK    t2_ID
FK    t3_ID
FK    t4_ID

t3
PK    t3_ID
        B

t4
PK    t4_ID
        C

With those tables, a cascade on delete operation is specified for the FK in t1 and for both FKs in t2. If one or more records are deleted from t3 or t4 the corresponding records in t2 and t1 are also deleted.

Questions

The delete functionality that I need is the reverse. I want the following to occur:

  1. Delete a record in t1
  2. Delete the corresponding record in t2
  3. If the corresponding record in t3 is not used anywhere else, i.e. that t3_ID is not anywhere else in t2, delete the corresponding record in t3
  4. Repeat step 3 for t4

I also need a similar functionality for the update operations.

  1. If the record in t3/t4 has no other entries in t2, then the value can simply be changed.
  2. If the record in t3/t4 is in at least one other record in t2, a new record will need to be created in t3/t4 and the reference in t2 will need to be updated.

How can I achieve this?

Was it helpful?

Solution

To propagate the deletion, you could do:

CREATE TRIGGER delete_unused_t2 AFTER DELETE on t1
FOR EACH ROW
BEGIN
    IF old.t2_ID NOT IN (SELECT t2_ID FROM t1)
    THEN BEGIN
        DELETE FROM t2
        WHERE t2.t2_ID = old.t2_ID;
    END;
    END IF;
END

If you want to do it periodically rather than in a trigger, you could do:

DELETE FROM t2
LEFT JOIN t1 USING (t2_ID)
WHERE t1_ID IS NULL
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top