数据库的三大设计范式
第一范式:
数据库中所有字段都是不可分割的原子值
create table students(
id int primary key,
name varchar(20),
address varchar(20)
);
字段值还能继续拆分的,就不满足第一范式
create table students(
id int primary key,
name varchar(20),
city varchar(20),
address varchar(20)
);
– 范式设计的越详细,对于某些实际操作可能更好,但不一定都是好处
第二范式:
必须满足第一范式的前提下,第二范式要求,除主键外的每一列都必须完全依赖于主键
create table myorder(
product_id int,
customer_id int,
product_name,
customer_name varchar(20),
primary key(product_id,customer_id)
);
除主键以外的其他列,只依赖主键的部分字段。怎么办?
拆表
create table myorder(
order_id int primary key,
product_id int,
customer_id
);
create table product(
id int primary key,
name varchar(20)
);
create table customer(
id int primary key,
name varchar(20)
);
分成三个表后,就满足了第二范式。
第三范式(3NF):
必须先满足第二范式,除开主键列的其他列之间不能有传递依赖关系。
create table myorder(
order_id int primary key,
product_id int,
customer_id,
customer_phone varchar(15)
);
phone不应该在上面的表中,即不能有传递依赖
create table customer(
id int primary key,
name varchar(20),
phone varchar(15)
);