Alex Rivera | Logout

Elegant way to remove orphan rows?

Asked 2011-06-22T20:14:27.057
20

I have a table with a lot of history entries that contain customer IDs.

There is a separate customer table. Occasionally some of the customer entries are removed.

Is there an easy way, without looping through each history entry, to drop all rows in the history table where the customer ID no longer exists because the customer row was deleted?

Edit
Report

1 Answer

6

You could use cascading with foreign keys to accomplish this. In the following example, any time a row is deleted from A, or an A_ID in A is changed, this change will automatically be reflected in table B. You can read more on foreign keys in the MySql Documentation.

CREATE TABLE A(
   A_ID INT, 
   PRIMARY_KEY(A_ID)
) TYPE=InnoDB;

CREATE TABLE B(
   B_ID INT,
   A_ID INT,
   CONSTRAINT FK_B_A FOREIGN KEY REFERENCES A(A_ID) ON DELETE CASCADE ON UPDATE CASCADE,
   PRIMARY_KEY(B_ID, A_ID)
) TYPE=InnoDB;
answered 2011-06-22T20:27:30.573

Your Answer