How to enforce referential integrity on Single Table Inheritance?

后端 未结 4 2021
一生所求
一生所求 2021-02-19 09:11

I\'ve read some of Bill Karwin\'s answers about single table inheritance and think this approach would be good for the setup I am considering:

Playlist
--------
         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-19 09:56

    What you can do is implement triggers on your Users and Team tables that execute whenever rows get deleted from either:

    User table:

    DELIMITER $$
    CREATE TRIGGER user_playlist_delete 
    BEFORE DELETE ON User FOR EACH ROW
    BEGIN
        DELETE a FROM Playlist a
        INNER JOIN UserPlaylist b ON a.id = b.id AND b.userId = OLD.id;
    END$$
    DELIMITER ;
    

    Team table:

    DELIMITER $$
    CREATE TRIGGER team_playlist_delete 
    BEFORE DELETE ON Team FOR EACH ROW
    BEGIN
        DELETE a FROM Playlist a
        INNER JOIN TeamPlaylist b ON a.id = b.id AND b.teamId = OLD.id;
    END$$
    DELIMITER ;
    

    What these triggers will do is each time a record is deleted from one of these tables, a DELETE operation will automatically execute on the Playlists table using the id that's about to be deleted (via an inner join).

    I have tested this and it works great.

提交回复
热议问题