開始使用免費開始

變更鍵的參照完整性行為

到目前為止,你已經實作了三個外鍵約束:

  1. professors.university_id 指到 universities.id
  2. affiliations.organization_id 指到 organizations.id
  3. affiliations.professor_id 指到 professors.id

這些外鍵目前的行為都是 ON DELETE NO ACTION。接下來,你要把 affiliations 中參照 organizations 的那個欄位行為改掉。如果某個 organization 被刪除,所有與之相關的 affiliation(不論是哪位教授)也都應該被刪除。

要變更鍵約束,不能用 ALTER COLUMN。你需要先DROP 該鍵約束,再ADD 一個新的,並指定不同的 ON DELETE 行為。

不過,在刪除約束時,你必須知道它的名稱。這些資訊也儲存在 information_schema 中。

本練習屬於課程

SQL 關聯式資料庫入門

檢視課程

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

-- Identify the correct constraint name
SELECT constraint_name, table_name, constraint_type
FROM information_schema.___
WHERE constraint_type = 'FOREIGN KEY';
編輯並執行程式碼