How to delete data from multiple tables?

前端 未结 5 919
广开言路
广开言路 2021-01-07 17:09

I have these tables:

event     (evt_id, evt_code, reg_id)

magnitude (mag_id, evt_id, value)

trace     (trace_id, pt_id)

point     (         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-07 18:04

    If you have control over your schema, I would make the schema use cascading deletes.

    From the article (the more pertinent portion translated for your example)

    CREATE TABLE point
    (
        pt_id integer PRIMARY KEY,
        evt_id integer REFERENCES event ON DELETE CASCADE
    )
    

    If you have cascades set up, then you can just delete from the main event table and all the other tables will be cleaned up automatically

    Otherwise, you need to delete all of the references first, then you delete the main table. You should do this in one transaction to keep data consistent

    BEGIN;
    DELETE FROM trace WHERE EXISTS 
        (SELECT 1 FROM point WHERE evt_id = 1139 AND trace.pt_id = point.pt_id);
    DELETE FROM point where evt_id = 1139;
    DELETE FROM magnitude where evt_id = 1139;
    DELETE FROM event where evt_id = 1139;
    COMMIT;
    

提交回复
热议问题