我有3张桌子:
表之间的关系是:
现在我必须从帖子表中删除帖子,但是我收到了错误。
我在下面使用此查询:
begin tran
declare @userid int = 68;
declare @postid int = 15;
delete from likes
where postid = @postid and userid = @userid
delete from comments
where postid = @postid and userid = @userid
delete from post
where postid = @postid and userid = @userid
rollback tran
我收到这些错误:
Msg 547,Level 16,State 0,Line 8
DELETE语句与SAME TABLE REFERENCE约束" Comments_fk3"冲突。冲突发生在数据库" development-topthat",table" dbo.Comments",column' CommentReplyID'。Msg 547,Level 16,State 0,Line 9
DELETE语句与REFERENCE约束冲突" Likes_fk1"。冲突发生在数据库" development-topthat",table" dbo.Likes",column' PostID'。
我在做错的地方需要帮助。怎么做到这一点?
答案 0 :(得分:0)
通过CommentReplyID
和自联接注释的外观,我怀疑你在评论表中有某种嵌套关系。
您需要删除CommentReplyId
与您删除的评论相匹配的记录。
begin tran
declare @userid int = 68;
declare @postid int = 15;
-- are you sure userid should be used here?
delete from likes where postid = @postid and userid = @userid
delete from comments c1 join comments c2 on c2.CommentReplyId = c1.CommentId where c1.postid = @postid and c1.userid = @userid
delete from comments where postid =@postid and userid = @userid
delete from post where postid = @postid and userid = @userid
rollback tran