删除外键级联

时间:2016-02-03 12:00:44

标签: sql sql-server

假设我有以下表格

User,Article,Comment

User上的Comment Article可以Article或写User

我想要的行为:

  • 当我删除Articles时,它应删除所有Comments和。{ Article
  • 当我删除Comments时,它应删除所有FOREIGN KEYS

所以我认为我应该使用CREATE TABLE [User]( UserId int PRIMARY KEY IDENTITY(1,1), Username nvarchar(50) NOT NULL ) CREATE TABLE [Article]( ArticleId int PRIMARY KEY IDENTITY(1,1), UserId int NOT NULL, FOREIGN KEY(UserId) references [User](UserId) ON DELETE CASCADE ) CREATE TABLE [Comment]( CommentId int PRIMARY KEY IDENTITY(1,1), UserId int Not NULL, ArticleId int NOT NULL , FOREIGN KEY(UserId) references [User](UserId) ON DELETE CASCADE, FOREIGN KEY(ArticleId) references [Article](ArticleId) ON DELETE CASCADE ) 并尝试将上述内容建模为以下

Comment

但问题出在Introducing FOREIGN KEY constraint 'FK__Comment__Article__32E0915F' on table 'Comment' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. 导致

CASCADE ON DELETE

我的问题是您如何对此行为进行建模并仍使用FOREIGEN KEYSint count = 1; for (int i = 0; i < flowerPack.length -1 && flowerPack[i] != null; i++) { if (flowerPack[i].equalsIgnoreCase(flowerPack[i+1])) { count++; } else { System.out.println(flowerPack[i] + "s - " + count); count = 1; } }

1 个答案:

答案 0 :(得分:2)

您应该只能删除评论中用户外键上的级联删除。

当用户被删除时,这将级联删除文章,这将依次删除评论:

CREATE TABLE [Comment](
   CommentId int PRIMARY KEY IDENTITY(1,1),
   UserId int Not NULL,
   ArticleId int NOT NULL ,
   FOREIGN KEY(UserId) references [User](UserId),
   FOREIGN KEY(ArticleId) references [Article](ArticleId) ON DELETE CASCADE
)