Elegant way to remove orphan rows?

后端 未结 5 2102
小蘑菇
小蘑菇 2021-02-19 02:51

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.

<
5条回答
  •  無奈伤痛
    2021-02-19 03:18

    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;
    

提交回复
热议问题