I’m creating two tables like this:
CREATE TABLE abc (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(64) NOT NULL,
created DATETIME DEFAULT '0000-00-00 00:00:00',
updated DATETIME DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE def (
abc_id INTEGER NOT NULL DEFAULT 0,
name VARCHAR(64) NOT NULL,
value LONGTEXT,
PRIMARY KEY(name, abc_id),
CONSTRAINT fk_def FOREIGN KEY(id)
REFERENCES abc(id) ON DELETE CASCADE ON UPDATE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
which should tell mysql to automatically delete the corresponding row from DEF when a row from ABC is deleted.
But this doesn’t work well with DROP operations.
If I try to drop table abc, I get a error saying a foreign key contraint fails.
It appears that I need to drop DEF first, and only then I can drop ABC. I don’t understand why, because dropping ABC should automatically drop DEF too, right? Or at least empty it by removing the rows that match the id from ABC…
No, databases don’t do this automatically, and for good reason. It’s there to prevent you corrupting your database and having invalid foreign keys pointing to non-existent tables. Everything is behaving as expected.
So yes, if you want to drop the tables, you’ll need to remove the dependent constraints first. The
ON DELETEforeign key clause is for when deleting rows, NOT dropping tables 🙂