【问题标题】:Can i delete user's questions and answers if i delete the user SQL如果我删除用户 SQL,我可以删除用户的问题和答案吗
【发布时间】:2020-01-18 22:50:10
【问题描述】:

我在 SQL 上有用户表问题表和答案表。 我想在删除级联问题上添加外键 user_ID 外键和回答 user_ID 外键,当我删除用户时,他的所有问题和答案也会被删除。但是 SQL 说:

在表“问题”上引入 FOREIGN KEY 约束“FK__questions__usID__1BC821DD”可能会导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。

我该怎么做。

【问题讨论】:

  • 请向我们展示您现有的代码。
  • 我这样做了:更改表问题添加约束 user_question_id_fkey 外键 (usID) 在删除级联时引用用户 (uID);但是当我对答案表尝试相同时,它返回了错误
  • SQL Server 不支持这种级联删除。您将需要使用 SP 来处理此问题或使用触发器。
  • 你能举个例子吗,因为我是 sql 新手

标签: sql sql-server tsql foreign-keys


【解决方案1】:

您希望questions(resp:answers)表上的外键引用users 表,并在从users 中删除用户的所有问题(resp:答案)时删除它表。

这应该按照设计工作:

alter table answers add constraint answers_users 
    foreign key(user_id)
    references users(user_id)
    on delete cascade
;

alter table questions add constraint questions_users 
    foreign key(user_id)
    references users(user_id)
    on delete cascade
;

考虑 this demo

-- create the tables
create table users (user_id int primary key);
create table questions(question_id int primary key, user_id int);
create table answers(answer_id int primary key, user_id int);

-- add the constraints
alter table answers add constraint answers_users 
    foreign key(user_id)
    references users(user_id)
    on delete cascade
;
alter table questions add constraint questions_users 
    foreign key(user_id)
    references users(user_id)
    on delete cascade
;

-- insert a few records - we have two users: 1 and 2
insert into users values (1), (2);
insert into questions values(1, 1), (2, 2);
insert into answers values(1, 1), (2, 2);

-- now delete user 1
delete from users where user_id = 1;

-- the corresponding record was removed from "questions"
select * from questions;

question_id | user_id
----------: | ------:
          2 |       2

-- ... and it was removed from "answers" as well
select * from answers;

answer_id | user_id
--------: | ------:
        2 |       2

【讨论】:

  • 它适用于一个新数据库,但不适用于我当前的数据库。无论如何感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-20
  • 2017-02-14
  • 2020-05-21
  • 1970-01-01
  • 1970-01-01
  • 2021-08-17
相关资源
最近更新 更多