MySQL - 数据库设计三范式

  • 第一范式 1NF

数据表中的所有字段都是不可分解的原子值

create table students2(
    -> id int primary key,
    -> name varchar(20),
    -> address varchar(30));

insert into students2 values(1,'张三','中国四川省成都市武侯区武侯大道100号');
insert into students2 values(2,'李四','中国四川省成都市武侯区京城大道200号');
insert into students2 values(3,'张三','中国四川省成都市高新区天府大道300号');

select * from students2;
+----+------+-------------------------------------+
| id | name | address                             |
+----+------+-------------------------------------+
|  1 | 张三  | 中国四川省成都市武侯区武侯大道100号    |
|  2 | 李四  | 中国四川省成都市武侯区京城大道200号      |
|  3 | 王五  | 中国四川省成都市高新区天府大道300号      |
+----+------+-------------------------------------+
3 rows in set (0.00 sec)

 显然address字段还可拆分,修改后满足第一范式。也不是拆的越细越好,实际应用中满足项目需求即可。

create table students3(
    -> id int primary key,
    -> name varchar(20),
    -> country varchar(30),
    -> province varchar(30),
    -> details varchar(30));
Query OK, 0 rows affected (0.01 sec)

insert into students3 values(1,'张三','中国','四川省','成都市武侯区武侯大道100号');
insert into students3 values(2,'李四','中国','四川省','成都市武侯区京城大道200号');
insert into students3 values(3,'王五','中国','四川省','成都市高新区天府大道300号');

select * from students3;
+----+------+---------+----------+---------------------------+
| id | name | country | province | details                   |
+----+------+---------+----------+---------------------------+
|  1 | 张三 | 中国     | 四川省    | 成都市武侯区武侯大道100号     |
|  2 | 李四 | 中国     | 四川省    | 成都市武侯区京城大道200号     |
|  3 | 王五 | 中国     | 四川省    | 成都市高新区天府大道300号     |
+----+------+---------+----------+---------------------------+
3 rows in set (0.00 sec)

 

  • 第二范式 2NF
在满足第一范式的前提下,第二范式要求除主键外的每一列都必须完全依赖主键
如果出现不完全依赖,只可能发生在联合主键的情况下
create table myOrder(
    -> product_id int,
    -> customer_id int,
    -> product_name varchar(20),
    -> customer_name varchar(20),
    -> primary key(product_id,customer_id));
问题:除主键外的其他列只依赖于部分主键
解决:拆表
create table myOrder(
    -> 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 myOrder(
    -> order_id int primary key,
    -> product_id int,
    -> customer_id int
    -> customer_phone varchar(11));

显然,customer_phone依赖于customer_id,和主键的关系通过customer_id传递,因此customer_phone不能放在该表中

create table myOrder(
    -> order_id int primary key,
    -> product_id int,
    -> customer_id int);

create table customer(
    -> id int primary key,
    -> name varchar(20)
    -> customer_phone varchar(11));

 

posted @ 2021-03-12 22:46  小王随便写  阅读(106)  评论(0)    收藏  举报