关于 SQLite 和级联外键的查询

Query regarding SQLite and Cascading foreign keys

我目前正在用 C# 编写一个应用程序,它使用 SQLite 数据库来存储用户输入的信息。该应用程序基本上是一个管理系统,用于在应用程序中称为 "Students" 的用户。这是我数据库中最重要的 table,所有其他 table 都与此 table 相关联。我想做的是当一个学生被移除时——他们离开 institute/get 被踢出等 - 是从所有其他 table 中移除他们的数据,这样数据就不再存在了需要。我编写的一些 Create table 语句的示例是:

CREATE TABLE student(studentID int(5) PRIMARY KEY NOT NULL, name string(16),...,DOB string(8) );

CREATE TABLE emergencyContact(emergencyID int(5) PRIMARY KEY NOT NULL, name string(16),..., contactNumber int(16));

CREATE TABLE emergencyContactOf(studentID int(5) FOREIGN KEY REFERENCES student('studentID'), emergencyID int(5) FOREIGN KEY REFERENCES emergencyContact('emergencyID');

我已阅读此内容,我的理解是,如果我包含 'ON DELETE CASCADE' 语句,则 EmergencyContactOf table 中的数据将被删除,因为 StudentID 密钥将不再存在于 Parent 中table。

但是,我的理解是 EmergencyContact table 中针对该特定学生的数据不会被删除,因为没有对 StudentID 的引用。

我的问题是,是否有办法从 table 中删除与该学生相关的数据?例如,如果我要在 EmergencyContact table 中包含一列,它将 StudentID 引用为外键,然后在 StudentID 从父 table 中删除时删除该行?这是解决这个特定问题的好方法吗?

我所有的其他tables也是这样设计的,其中数据在不同的tables中,然后通过关系[=链接回学生table 26=]s 所以这也适用于我拥有的所有其他 tables。

谢谢。

嗯,我在这里看到两种情况。如果两个学生有相同的紧急联系人怎么办,比如说两个人都有他们的父亲作为紧急联系人?

  1. 如果在这种情况下,您在紧急联系人中只存储了一个记录(父亲)table,如果只有其中一个离开,您不想删除紧急联系人。你会删除另一个人的紧急联系人。所以你需要额外的逻辑,何时删除紧急联系人。你可以把它放在触发器中。
  2. 您使用了一种不太复杂的方法,紧急联系人 table 中的多行可以映射到现实生活中的一个人。在这种情况下,您可以将对学生的引用直接拉入紧急联系人 table 并在那里使用 ON DELETE CASCADE

    CREATE TABLE student
                 (studentid int(5),
                  name string(16),
                  ...
                  PRIMARY KEY (studentid),
                  ...);
    ...
    CREATE TABLE emergencycontact
                 (emergencycontactid int(5),
                  studentid int(5),
                  name string(16),
                  ...
                  PRIMARY KEY (emergencycontactid),
                  FOREIGN KEY (studentid)
                              REFERENCES student
                                         (studentid),
                  ...);
    

第二个可能很诱人,但 "clean way" 是第一个,因为第二个允许矛盾的数据。根据您发布的内容,您已经在 "clean way" 上了。但是提到需要触发器。

My question is, is there a way to remove the data from this table also that is relevant to that Student? For example, if I was to include a column in the EmergencyContact table which would reference the StudentID as a Foreign Key and then remove that row if the StudentID is ever deleted from the parent table? Is this a good solution to this particular problem?

如果多个学生有相同的紧急联系人会怎样?如果不需要,您不想复制数据 - 这就是 emergencyContactOf table 的全部意义所在,可以有效地在学生和紧急联系人之间建立多对多关系。所以你不想做你描述的事情。

您可以定期(每月、每年、在清除学生花名册之后等等)运行 删除 emergencyContact 中未出现在 emergencyContactOf 中的行:

DELETE FROM emergencyContact
WHERE emergencyID NOT IN (SELECT emergencyID FROM emergencyContactOf)

之类的。