假设我有三个表,名为“类别”、“子类别”和“prodcut”,该表的结构如下
category
====Catid=======CatName=====
| 1 | DRESS |
| 2 | FOOD |
subcategory
====SubCatid=======SubCatName========Catid=====
| 1 | cake | 2 |
| 2 | t-shirt | 1 |
| 3 | chocolate | 2 |
| 4 | shirt | 1 |
product
====productid=======productName========SubCatid=====
| 1 | p1 | 2 |
| 2 | p2 | 1 |
| 3 | p3 | 1 |
| 4 | p4 | 2 |现在,我想让我的应用程序像这样,如果子类别表中的任何一个类别作为记录出现,用户就不能删除这个类别。用户必须从子类别表中删除它,在该用户可以从类别表中删除它之后。同时,用户也不能从产品表中的子类别中删除记录。我试过用Foreignkey,但我无法理解解决这个问题的正确方法。请帮我解决这个问题。
发布于 2015-12-02 10:04:02
您需要使用外国钥匙和限制引用选项:
alter table `subcategory` add foreign key (`Catid`) references `category`(`Catid`) on update cascade on delete restrict因此,如果有人试图删除具有子类别的类别,MySQL将禁止此操作并输出错误:
Cannot delete or update a parent row: a foreign key constraint fails产品表也是一样的:
alter table `product` add foreign key (`SubCatid`) references `subcategory`(`SubCatid`) on update cascade on delete restricthttps://stackoverflow.com/questions/34039807
复制相似问题