Search code examples
mysqldata-modelingdelete-rowone-to-one

MySQL Cascade delete if one-to-one relationship


Imagine a database that stores book titles and authors. When I delete a book title, I also want to delete the author - but only if they have no other book titles associated with them.

Is there a way to do that?

Or, perhaps, you can recommend how I'd structure my tables differently to get around this. This is a simplified example of an app where I'm in charge of the data modelling; perhaps by asking the above question I've clearly structured my data poorly.


Solution

  • This is one of those "chicken and egg" data modeling scenarios like a department needing employees, and a department's manager being an employee in the department. Normally, you'd think of the author as the "parent" since it can have many books and book must be authored; but without a book that they have authored, they are not an author.

    So it is not really a poor structure, so much as a complication of the relationship you are representing. CASCADE will not work for you; but you could use an AFTER DELETE trigger on your "books" table to check if the author of the deleted book has any books remaining and delete them if they don't.