经过几天给韶关某个高校进行数据库设计的实训,对数据库设计的过程有了更加深刻的理解。
一、数据库设计的步骤
(1)了解功能需求
在设计数据库之前,设计人员必须要先了解系统的功能需求。这里可以通过阅读产品需求规格说明书,与项目相关人员(比如项目经理、客户等)进行充分沟通。
(2)定义实体
了解系统功能需求之后,设计人员通过分析系统功能定义出系统有哪些实体。比如:到酒店开房。这里应该至少包含两个实体:客人和房间。
在定义出实体以后,我们还要定义实体的属性。例如:
客人:姓名、性别、手机号码、证件号码、证件类型(身份证、驾驶证、通行证等等)…
房间:房号、房间类型(单人房、双人房、豪华房等等)、入住时间、离开时间、房间状态(已入住、未入住)…
(3)绘制E-R图
定义好实体之后,接下来我们应该根据实体以及实体之间的关系绘制出E-R图。比如:
长方形代表实体,椭圆形代表实体的属性,菱形代表实体之间的关系。
(4)把E-R图转换成模型
绘制出E-R图之后,我们需要根据它来构建物理模型。构建物理模型可以使用一些工具,比如目前比较流行的PowerDesigner。
(5)检查模型
完成模型设计后,我们还要检查模型是否满足第三范式的要求。如果不满足就需要重新对模型进行修正,直到满足第三范式的要求为止。
比如说,上面的模型并没有满足第三范式的要求。因为customer和room这两个表都存在一些与该表没有直接关系的字段。如果要满足第三范式要求,就需要把模型修改为:
上面模型增加了三个表,分别是identity_type(证件类型表)、register(入住登记表)、room_type(房间类型表),经过对模型的修正后,已经满足第三范式的要求。
(5)根据模型定义数据库
不同数据库的SQL命令可能会有小小差别。比如我们这里使用了MySQL数据库。
定义数据库的命令:DDL
#创建数据库
create database 数据库名;#删除数据库
drop database 数据库名;#查询数据库
show databases;#选定数据库
use 数据库名;#创建表
create table 表名 (列名 数据类型 [primary key] [auto_increment],列名 数据类型 [not null] [unique] [default '默认值'] [comment '字段说明'],列名 数据类型 [not null] [unique] [default '默认值'] [comment '字段说明'],...[constraint 外键名 foreign key(外键列) references 表名(主键列) [on update|delete cascade]]
);#删除表
drop table 表名;
下面根据模型定义数据库:
#创建数据库
create database hotel;#查询数据库
show databases;#选定数据库
use hotel;#证件类型表
create table identity_type (identity_type_id int primary key auto_increment, identity_type_name varchar(50) not null comment '证件类型名称'
);#客人表
create table customer (cust_id int primary key auto_increment,cust_name varchar(255) not null unique default '' comment '客人名称',mobile varchar(11) default '' comment '手机号码',identity_num varchar(50) not null unique default '' comment '证件号码',identity_type_id int not null comment '外键列,引用证件类型表',constraint fk_cust_identity_type foreign key(identity_type_id) references identity_type(identity_type_id)
);#房间类型
create table room_type (room_type_id int primary key auto_increment, room_type_name varchar(50) not null comment '房间类型名称'
);#房间
create table room (room_id int primary key auto_increment, room_num varchar(10) not null comment '房号',room_type_id int not null comment '外键列,引用房间类型表',status int not null comment '房间状态,1代表未入住,2代表已入住',constraint fk_room_type foreign key(room_type_id) references room_type(room_type_id)
);#入住登记表
create table register (cust_id int not null comment '外键,引用客人表',room_id int not null comment '外键,引用房间表',in_time datetime not null comment '入住时间',out_time datetime comment '离开时间',constraint fk_register_cust foreign key(cust_id) references customer(cust_id),constraint fk_register_room foreign key(room_id) references room(room_id)
)
至此,数据库设计阶段的任务已经完成。
二、总结
数据库设计其实并不难,本人觉得比较难的地方在于开始的分析阶段。就是如何根据客户需求把数据库里面的实体,以及实体之间的关系分析出来。所以,在数据库设计阶段,我们应该把重点放在业务需求的分析上,准确把握客户的需求,这样才能够设计出一套比较好的数据库。