3、数据库的三大设计范式

1、第一范式

——1NF:数据表中所有的字段都是不可划分的原子值

【语句实现】

//创建一个名为students2的数据表

    > create table students2(

    -> id int primary key,

    -> name varchar(20),

    -> address varchar(30));

//添加记录

    > insert into students2 value(1,'张三','河北省保定市易县');

    >insert into students2 value(2,'李四','河北省保定市阜平县');

    > insert into students2 value(3,'王五','河北省保定市安新县');

上述数据表的address字段是可以在进行划分的(所以不满足1NF)具体实现如下:

//创建students3

    > create table students3(

    -> id int,

    -> name varchar(20),

    -> privence varchar(20),

    -> city varchar(20),

    -> details varchar(30));

//添加记录

    > insert into students3 value(1,'张三','河北省','保定市','易县');

    >insert into students3 value(1,'张三','河北省','保定市','阜平');

    >insert into students3 value(1,'张三','河北省','保定市','安新县');

上述就满足第一范式(字段分的越详细的话,对于某些实际操作可能更好,但是也不一定)

2、第二范式

——2NF:必须满足第一范式的前提下,满足第二范式要求:表中除主键以外的每一列都必须完全依赖于主键

——如果出现不完全依赖,只可能发生在联合主键的情况下

订单表

    >create table myorder(

    -> product_id int,

    -> customer_id int,

    -> product_name varchar(20),

    -> customer_name varchar(20),

    -> primary key(product_id,customer_id));

问题:出主键的其他列,只依赖于主键的部分字段(因为此时主键为联合主键,但是product_name只与product_id有关,同理customer_name只与customer_id有关系)

——拆表——>满足第二范式

<1>表myorder

    > create table myorder(

    -> order_id int primary key,

    -> product_id int,

    -> customer_id int);

<2>表product

    > create table product(

    -> id int primary key,

    -> name varchar(20));

<3>表customer

    >create table customer(

    -> id int primary key,

    -> name varchar(20));

将一个表拆为三个表满足第二范式!!!

3、第三范式

——3NF:首先必须要满足第二范式,并主键列的其他列之间不能有传递依赖

    >create table myorder(

    -> order_id int primary key,

    -> product_id int,

    -> customer_id int,

    ->customer_phone varchar(11));

这里的customer_phone虽说依赖于主键,但是与customer_id有传递依赖,所以不满足第二范式

——将其放到 customer中

    >create table customer(

    -> id int primary key,

    -> name varchar(20),

    -> phone varchar(11));

猜你喜欢

转载自www.cnblogs.com/guo-2020/p/12306895.html