關係與外來鍵約束

2022-07-04 19:45:10 字數 1249 閱讀 7923

id

學生科目

成績

create

table

scores(

id int

primary

keyauto_increment,

stuid

int,

subid

int,

score

decimal(5,2

));

一對一(假設獨身子女)

學生表:(id,學生名字,科目,成績,motherid,fatherid)

母親表:(id,母親名字)

父親表:(id,父親名字)

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

母親表:(id,母親名字)

父親表:(id,父親名字)

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

老師表:(id,老師名字)

alter

table scores add

constraint stu_sco foreign

key(stuid) references students(id);

create

table

scores(

id int

primary

keyauto_increment,

stuid

int,

subid

int,

score

decimal(5,2

),foreign

key(stuid) references

students(id),

foreign

key(subid) references

subjects(id)

);

alter

table scores add

constraint stu_sco foreign

key(stuid) references students(id) on

delete

cascade;

restrict(限制):預設值,拋異常

cascade(級聯):如果主表的記錄刪掉,則從表中相關聯的記錄都將被刪除

set null:將外來鍵設定為空

no action:什麼都不做

mysql約束與外來鍵 MySQL 外來鍵與約束

外來鍵的建立 建表如下 create table parent id int not null,primary key id type innodb create table child id int,parent id int,foreign key parent id references pa...

mysql外來鍵和外來鍵約束

1.mysql中 鍵 和 索引 的定義相同,所以外來鍵和主鍵一樣也是索引的一種。不同的是mysql會自動為所有表的主鍵進行索引,但是外來鍵字段必須由使用者進行明確的索引。用於外來鍵關係的字段必須在所有的參照表中進行明確地索引 2.如果表a的主關鍵字是表b中的字段,則該字段稱為表b的外來鍵,表a稱為主...

mysql 外來鍵和外來鍵約束

1.外來鍵 如果公共關鍵字在乙個關係中是主關鍵字,那麼這個公共關鍵字被稱為另乙個關係的外來鍵。就是a表的主鍵,被用到了b表中,此時它就成了外來鍵 2.外來鍵約束 如果想要插入或者更新外來鍵的值,資料庫會和引用表中字段的資料進行驗證,如果插入或更改的值不在被引用的表中,則插入失敗 外來鍵的作用就是保證...