Question

I'm writing an application that requires all users to access data on a central database using MySQL, and I was wondering something.

Let's say I have this setup.

CREATE TABLE A
(
    id   INT PRIMARY KEY AUTO_INCREMENT,
    data INT NOT NULL;
);

CREATE TABLE B
(
   id    INT PRIMARY KEY AUTO_INCREMENT,
   a_id  INT,
   FOREIGN KEY (a_id) REFERENCES A(id) ON DELETE SET NULL
);

Now, the way I want this set up is, table A must ALWAYS be referenced by a row in table B. However, a row in table B may or may not reference a row in table A. The relationship is 1:n in that multiple rows in table B can reference a single row in table A. I am just wondering if it is possible to have the MySQL database automatically delete a row in A if it is no longer referenced by any row in table B.

The idea here is that I can simply set a_id in table B to NULL and have the database cleanup whatever is left. I guess that's similar to Java garbage collection now that I think about it. If there is no key to automatically enforce the constraint, would a trigger executed after an update work?

EDIT: Adding in the additional relationship constraint.

Was it helpful?

Solution

Run the following query at a specific interval:

DELETE tableA
FROM tableA LEFT JOIN tableB B ON A.id = B.a_id
WHERE B.a_id IS NULL;

Or, to maintain real-time consistency, you could create an OnChange trigger on tableB that performs similar.

OTHER TIPS

Is there a reason for the table structure you are using? The way you are using foreign keys looks backwards to me. Instead of placing your key in table B, you could move it to table A.

This would give you a structure that looked more like:

tableA columns        tableB columns
  id
  b_id                id
  [values]            [values]

  fk: a.b_id=b.id

A record added to table A would require a corresponding field in table B, but B would be free to have no values in table A. Then if you wanted to clean out the values in table A, you could simply use:

delete from tableA where b_id=[recordIdToNull];

You could even set A's foreign key up to cascade actions taken on B, so any values deleted from B would also delete the corresponding rows in A.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top