如何在多对一关系上使用DELETE ON CASCADE [英] How to use DELETE ON CASCADE on many-to-one relation

查看:107
本文介绍了如何在多对一关系上使用DELETE ON CASCADE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以有人帮我.我正在尝试某些东西,但是对(my)SQL不熟悉.

May someone help me out. I'm trying something, but I'm (too) new to (my)SQL.

我使用两个表格:项目和类别.表格项目有一个带有外键的字段:category_id.

I use two tables: Items and Categories. Table Items has a field with foreign key: category_id.

我希望表类别保持整洁.因此,如果项目"中没有任何项目属于类别"中的"X"类别,则应从类别"中删除"X"类别.您如何确定这一点.我通过使用DELETE ON CASCADE进行猜测,但是到目前为止,当我从类别"中删除类别时,它只是从项目"中删除相应的项目.

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.

非常感谢您的帮助!

推荐答案

ON DELETE CASCADE是删除引用的行时删除行的一种方法.这意味着:

ON DELETE CASCADE is a way of deleting a row when a row it references is deleted. This means:

  • 您在表A中有一行
  • 表B中有一行引用了表A中的一行
  • 您删除表A中的行
  • 数据库删除表B中的相应行

因此,您有项目,并且每个项目都属于一个特定的类别.在您的项目表中,您有一个category_id(请纠正拼写),它指向categorys表中的一行.因此,根据您的情况:

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:

  • 您有一个类别
  • 您有一个引用类别的项目
  • 您删除类别
  • 数据库删除与该类别相对应的所有项目

您要的是另一种方式:

  • 您有物品
  • 您删除特定类别中的最后一个项目
  • 数据库去查找该类别并将其删除

由于以下两个原因,无法使用ON DELETE CASCADE进行此操作:

There's no way to do this with ON DELETE CASCADE, for two reasons:

  1. 在将第一个项目插入其中之前,您将如何创建一个空类别?数据库必须立即将其删除.
  2. 数据库将不得不做很多额外的工作来扫描表.它不知道"项目#23082是类别中的最后一个项目.为此,必须以某种方式跟踪类别中的项目数.

所有这些都源于以下事实,即ON DELETE CASCADE保持参照完整性的一种方式.也就是说,这是数据库为您提供强烈保证的一种方式,即如果您在项目#9847上看到类别#20393,则当您查找类别#20393 您知道它存在.这不是不是省力设备. :)这就是为什么其他选项是ON DELETE SET NULLON DELETE RESTRICT的原因:它们还保证完整性,但它们不是删除而是删除了错误的引用或阻止了原始删除的发生.

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.

因此,答案是,如果您担心类别为空,则必须编写cron作业来定期清理该表,或者使用某种ON DELETE触发器.

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.

这篇关于如何在多对一关系上使用DELETE ON CASCADE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆