Elegant way to remove orphan rows?

后端 未结 5 2091
小蘑菇
小蘑菇 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;
    
    0 讨论(0)
  • 2021-02-19 03:20
    DELETE h.* FROM history h
    LEFT JOIN customer c ON h.customer_id = c.id
    WHERE c.id IS NULL
    

    I'm typing this from the top of my head, but you get the idea hopefully.

    Delete syntax documentation

    0 讨论(0)
  • 2021-02-19 03:25

    How about:

    DELETE FROM history_table 
    WHERE customer_id NOT IN (SELECT customer_id FROM customer);
    
    0 讨论(0)
  • 2021-02-19 03:26
    delete from history_table where customer_id not in (select customer_id from customers)
    

    did you mean something like this?

    0 讨论(0)
  • 2021-02-19 03:37
    DELETE FROM CUSTOMER_HISTORY CH
    WHERE NOT EXISTS (SELECT 1 FROM CUSTOMER C WHERE C.CUSTOMER_ID = CH.CUSTOMER_ID)
    
    0 讨论(0)
提交回复
热议问题