I have table1(id_table1) and table2(id_table2, id_table1). I’d like to remove records in table2 (under a given condition) but then also remove items in table1 that have no more relationships to table2. What is the most efficient way to do that in SQL? I’m using mySql.
Thanks in advance!
If you use InnoDB, add a foreign key constraint with an
ON DELETE CASCADE. This will automatically delete the rows if the relationship is no longer correct. That way, you don’t have to query the database after deleting rows in table2 to check if the relation is still intact.Foreign key constraints