1. 程式人生 > >關係與外來鍵約束

關係與外來鍵約束

關係

  • 建立成績表scores,結構如下

    id
    學生
    科目
    成績

  • 思考:學生列應該存什麼資訊呢?
  • 答:學生列的資料不是在這裡新建的,而應該從學生表引用過來,關係也是一條資料;根據正規化要求應該儲存學生的編號,而不是學生的姓名等其它資訊
  • 同理,科目表也是關係列,引用科目表中的資料
  • 建立表的語句如下
create table scores(
id int primary key auto_increment,
stuid int,
subid int,
score decimal(5,2)
);
一對一(假設獨身子女)
學生表:(id,學生名字,科目,成績,motherid,fatherid)
母親表:(id,母親名字)
父親表:(id,父親名字)
一對多
學生表:(id,學生名字,科目,成績,motherid,fatherid)
母親表:(id,母親名字)
父親表:(id,父親名字)

多對多
學生表:(id,學生名字,科目,成績,motherid,fatherid,teacherid)
老師表:(id,老師名字)

外來鍵

  • 思考:怎麼保證關係列資料的有效性呢?任何整數都可以嗎?
  • 答:必須是學生表中id列存在的資料,可以通過外來鍵約束進行資料的有效性驗證
  • 為stuid新增外來鍵約束
alter table scores add constraint stu_sco foreign key(stuid) references students(id);
  • 此時插入或者修改資料時,如果stuid的值在students表中不存在則會報錯
  • 在建立表時可以直接建立約束
create table scores(
id int primary key auto_increment,
stuid 
int, subid int, score decimal(5,2), foreign key(stuid) references students(id), foreign key(subid) references subjects(id) );

外來鍵的級聯操作

  • 在刪除students表的資料時,如果這個id值在scores中已經存在,則會拋異常
  • 推薦使用邏輯刪除,還可以解決這個問題
  • 可以建立表時指定級聯操作,也可以在建立表後再修改外來鍵的級聯操作
  • 語法
alter table scores add constraint stu_sco foreign
key(stuid) references students(id) on delete cascade;
  • 級聯操作的型別包括:

    restrict(限制):預設值,拋異常
    cascade(級聯):如果主表的記錄刪掉,則從表中相關聯的記錄都將被刪除
    set null:將外來鍵設定為空
    no action:什麼都不做