[英]Use two foreign key in table with 'on delete cascade'
CREATE TABLE Comments(
Id INT PRIMARY KEY IDENTITY(0,1),
TEXT NOT NULL,
Date Date NOT NULL ,
Point INT NOT NULL DEFAULT(0),
ID_User INT FOREIGN KEY REFERENCES Users(Id) ON DELETE CASCADE NOT NULL,
ID_Post INT FOREIGN KEY REFERENCES Posts(Id) NOT NULL
)
當我從“用戶”表中刪除“用戶”時,它向我顯示“注釋”表具有其他“參考鍵”的錯誤。 我該怎么辦?
DELETE語句與REFERENCE約束“ FK__Comments__ID_Pos__76969D2E”沖突。 在數據庫“ Facebook”的表“ dbo.Comments”的列“ ID_Post”中發生了沖突。
如果要刪除用戶記錄,則需要刪除外鍵表中的記錄。
在這種情況下,您需要刪除“ Comments
表中的記錄。
DELETE from dbo.Commnts
Where ID_User = "userid"
然后,您可以從“ Users
表中刪除用戶記錄
我對此做了一些工作,您在這里引用的外鍵沒有錯誤。 您可能已經在其他一些表中引用了注釋ID。
這就是我嘗試過的
CREATE TABLE Users(
Id int primary key
)
CREATE TABLE posts(
Id int primary key
)
insert into Users values(1);
insert into Users values(2);
insert into posts values(3);
insert into posts values(4);
CREATE TABLE Comments(
Id INT PRIMARY KEY IDENTITY(0,1),
ID_User INT FOREIGN KEY REFERENCES Users(Id) ON DELETE CASCADE NOT NULL,
ID_Post INT FOREIGN KEY REFERENCES Posts(Id) NOT NULL
)
insert into Comments values(1,3);
insert into Comments values(2,4);
DELETE
FROM Users
WHERE id = 1 --this works fine
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.