且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL ON DELETE CASCADE,删除是通过什么方式发生的?

更新时间:2023-02-02 23:32:48

当您删除表 Courses 上的某些内容时,Cascade 将起作用.表 BookCourses 上任何引用表 Courses 的记录都将被自动删除.

Cascade will work when you delete something on table Courses. Any record on table BookCourses that has reference to table Courses will be deleted automatically.

但是当您尝试删除表 BookCourses 时,只有表本身会受到影响,而不会影响 Courses

But when you try to delete on table BookCourses only the table itself is affected and not on the Courses

后续问题:为什么表 Category 上有 CourseID?

也许你应该将你的架构重组为这个,

Maybe you should restructure your schema into this,

CREATE TABLE Categories 
(
  Code CHAR(4) NOT NULL PRIMARY KEY,
  CategoryName VARCHAR(63) NOT NULL UNIQUE
);

CREATE TABLE Courses 
(
  CourseID INT NOT NULL PRIMARY KEY,
  BookID INT NOT NULL,
  CatCode CHAR(4) NOT NULL,
  CourseNum CHAR(3) NOT NULL,
  CourseSec CHAR(1) NOT NULL,
);

ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;