我有一个产品、类别和“productsInCategories”的数据库,看起来像:
用户
id?  name  ?
????????????
1 ?  john  ?
69?  jane  ?
产品
id?  name  ? cost ?description?
???????????????????????????????
21?snickers?  23  ? foo       ?
34?  mars  ?  20  ? bar       ?
37?  daim  ?  21  ? oofrab    ?
79? banana ?  8   ? foobar    ?
80?  apple ?  10  ? barfoo    ?
类别
id?  userId ?   name  ?
???????????????????????
10?    69   ?chocolate?
55?    69   ?favorites?
20?    1    ? fruit   ?
产品分类
categoryId?productId?
?????????????????????
    10    ?   21    ?
    10    ?   34    ?
    20    ?   79    ?
    20    ?   80    ?
    55    ?   21    ?
    55    ?   37    ?
这产生了一些可以被视为:
Users
   john
      fruit
         banana
         apple
   jane
      chocolate
         snickers
         mars
         daim
      favorites
         snickers
         daim
当我想获得某个类别的所有产品时,我会执行以下操作:
SELECT *
FROM Products
        INNER JOIN ProductsInCategories
        ON Products.Id=ProductsInCategories.product
        WHERE category=@0
,@0=categoryId
一切正常,插入或删除产品非常简单。但是我现在有一个问题,我无法解决问题。
即删除类别。我将如何继续这样做?我已经工作了几个小时,但似乎无法让它工作。如果用户删除了一个类别,我希望所有仅存在于该类别中的产品与相关联的 productInCategories-records 一起被删除。如果说用户“Jane”删除了她的类别“巧克力”,那么我想删除产品“火星”而不是“士力架”或“火星”,因为它们也存在于“收藏夹”类别中
除非您在架构中设置级联删除,否则您需要使用 3 个删除语句,每个表一个。
-- Delete category 10 from Categories table.
DELETE FROM Categories WHERE Id=10;
-- Delete category 10 from ProductsInCategories table.
DELETE FROM ProductsInCategories WHERE CategoryId=10;
-- Delete all products that are no longer in a category    
DELETE Products
FROM Products
LEFT JOIN ProductsInCategories
  ON ProductId=Products.Id
WHERE ProductId IS NULL;
| 归档时间: | 
 | 
| 查看次数: | 1379 次 | 
| 最近记录: |