数据库设计的三大范式
一、第一范式 1NF
描述:数据库中所有字段都是不可分割的原子值。
字段值还可以拆分就不满足第一范式。当然,在实际开发中,要视情况而定,是否拆分的更详细。
二、第二范式 2NF
描述:必须是在满足第一范式的前提下,除主键外的每一列都必须完全依赖于主键。
如果要出现不完全依赖,只可能发生在联合主键的情况下。
比如说有这样一张订单表:
create table order(
product_id int,
customer_id int,
product_name varchar(20),
customer_name varchar(20),
primary key(product_id,customer_id)
);
那么这张表就有一个问题:这张表的主键是product_id 和 customer_id 构成的联合主键,而product_name 只与 product_id 有关,customer_name 只与 customer_id 有关。可见,在这张表中,除主键以外的其他列,只依赖于主键的部分字段,因此这张表的设计不满足第二范式。
如何使其满足第二范式?
拆表
create table order(
order_id int primary key,
product_id int,
customer_id int
);
create table product(
id int primary key,
name varchar(20)
);
create table customer(
id int primary key,
name varchar(20)
);
如此,便满足第二范式。
三、第三范式 3NF
描述:必须满足第二范式,且除主键外的其他列,不能存在传递依赖。
create table order(
order_id int primary key,
product_id int,
customer_id int,
customer_phone varchar(11)
);
在上表中,customer_phone 依赖于 customer_id,而 customer_id 又依赖于 order_id ,这样便产生了传递依赖,应该把 customer_phone 放入 customer 表中。
create table order(
order_id int primary key,
product_id int,
customer_id int
);
create table customer(
id int primary key,
name varchar(20),
phone varchar(11)
);