主要介紹一下個人對主鍵(primary key)、外鍵(foreign key)、候選鍵(Candidate key)、超鍵(super key)、references的總結
概念:
主鍵:用戶選擇元組標識的一個候選鍵,主鍵不允許為空
外鍵:來描述兩個表的關系,外鍵可為空
超鍵:能唯一的標識元組的屬性集
候選鍵:不含有多余屬性的超鍵
實例:
假如有以下學生和教師兩個表:
Student(student_no,student_name,student_age,student_sex,student_credit,teacher_no)
Teacher(teacher_no,teacher_name,teacher_salary)
超鍵:Student表中可根據學生編號(student_no),或身份證號(student_credit),或(學生編號,姓名)(student_no,student_name),或(學生編號,身份證號)(student_no,student_credit)等來唯一確定是哪一個學生,因此這些組合都可以作為此表的超鍵
候選鍵:候選鍵屬於超鍵,且是最小的超鍵,即如果去掉超鍵組合中任意一個屬性就不再是超鍵了。Student表中候選鍵為學生編號(student_no),身份證號(student_credit)
主鍵:主鍵是候選鍵中的一個,可人為決定,通常會選擇編號來作為表的主鍵。現分別選取student_no,teacher_no作為Student表,Teacher表的主鍵
外鍵:teacher_no為兩個表的公共關鍵字,且是Teacher表的主鍵,因此teacher_no是Student表的外鍵,用來描述Student表和Teacher表的關系
--References用法
創建一張Student表:
Create table Student(
student_no number(10) not null,
student_name varchar2(10) not null,
student_age number(4) not null,
student_sex varchar2(4) not null,
student_credit varchar2(18) not null,
teacher_no number(10) not null,
constraint PK_Student primary key(student_no) --設置主鍵
);
創建一張Teacher表:
Create table Teacher(
teacher_no number(10) not null,
teacher_name varchar2(10) not null,
teacher_salary number(10) not null,
constraint PK_Teacher primary key(teacher_no) --設置主鍵
);
--創建外鍵約束
alter table Student add constraint FK_Student_References_Teacher (teacher_no) references Teacher(teacher_no);