May someone help me out. I\'m trying something, but I\'m (too) new to (my)SQL.
I use two tables: Items and Categories. Table Items has a field with foreign key: cate
ON DELETE CASCADE
is a way of deleting a row when a row it references is deleted. This means:
So you have items, and each item belongs to a particular category. In your items table, you have a category_id (and please fix your spelling) that refers to a row in the categories table. So, in your situation:
What you're asking for is sort of the other way around:
There's no way to do this with ON DELETE CASCADE
, for two reasons:
This all stems from the fact that ON DELETE CASCADE
is a way of maintaining referential integrity. That is, it's a way for the database to give you a strong guarantee that if you see category #20393 on item #9847, when you go look for category #20393 you know it exists. It is not a labor saving device. :) This is why the other options are ON DELETE SET NULL
and ON DELETE RESTRICT
: they also guarantee integrity, but instead of deleting, they remove the bad reference or prevent the original delete from occurring.
So the answer is, you will have to either write a cron job to periodically clean that table or use some kind of ON DELETE trigger, if you're worried about empty categories.