方立勋_30天掌握JavaWeb_数据库表设计
定義外鍵約束
丈夫、妻子表:
妻子用一個husband_id來說明wife丈夫是哪個。
一對多對象表設計
部門、員工表:
一個部門可以有多個員工,員工表通過department_id說明屬于哪個部門。
一對多或多對一的對象存到數據庫時,表的設計方案
部門和員工
create table department
(
id int primary key,
name varchar(40)
);
create table employee
(
id int primary key,
name varchar(40),
salary decimal(8,2),
department_id int,
constraint department_id_FK foreign key(department_id) references department(id)
);
多對多對象表關系設計
教師、學生表:
通過一張中間表teacher_student來說明關系。
多對多對象的表的設計(老師和學生)
create table teacher
(
id int primary key,
name varchar(40),
salary decimal(8,2)
);
create table student
(
id int primary key,
name varchar(40)
);
create table teacher_student
(
teacher_id int,
student_id int,
primary key(teacher_id,student_id),
constraint teacher_id_FK foreign key(teacher_id) references teacher(id),
constraint student_id_FK foreign key(student_id) references student(id)
);
一對一對象表設計(具體主從關系)
人、身份證表:
省份證是從表,直接用主鍵id作為外鍵。
一對一的對象的數據庫設計
create table person
(
id int primary key,
name varchar(40)
);
create table idcard
(
id int primary key,
city varchar(40),
constraint id_FK foreign key(id) references person(id)
);
自連接的表設計
家譜管理系統。
打個比如:你爺爺生了你爸爸,你爸爸生你,你又生了孩子。
Person對象:id、姓名、Person(記住爸爸)、Children(記住孩子)。
這樣的表設計,直接存入了一張表,用一個字段parent_id來說明。parent_id 來自id,需要加外鍵約束,不能加非空約束。
create table person
(
id int primary key,
name varchar(40),
parent_id int,
constraint parent_id_FK foreign key(parent_id) references person(id)
);
當然顯示實際開發中,有的為了查詢效率,并不會這么設計,可能會去增加冗余字段加快查詢速度。
總結
以上是生活随笔為你收集整理的方立勋_30天掌握JavaWeb_数据库表设计的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 方立勋_30天掌握JavaWeb_使用h
- 下一篇: 方立勋_30天掌握JavaWeb_JDB