2015-12-02 147 views
1

假設我有三個表名爲類別,子類別和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,但我無法理解解決此問題的正確方法。請幫我解決這個問題。

回答

0

您需要使用Foreign Keys與RESTRICT參考選項:

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 restrict 
+0

並在產品表上添加同樣的東西嗎?就像我刪除子類別並且它出現在產品表中一樣,它也可以被刪除? –

+0

哦你已經回答了我的問題。謝謝。公認 –

相關問題