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: category_id.
I want the table Categories to be kept tidy. So when no item in Items is of category X in Categories, the category X should be deleted from Categories. How do you establish that. I guessed by using DELETE ON CASCADE, but so far it was only deleting corresponding items from Items when I deleted a categorie from Categories.
Thanks a lot for helping me!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With