社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  DATABASE

MySQL 逆范式

周行知 • 5 年前 • 271 次点击  

数据库设计需要遵守三范式

1.原子性

数据不可以再分割

2.数据没有冗余

Order -goods

id a   编号相同  下单时间 商品信息1 商品价格 商品产地

id b   编号相同  下单时间 商品信息2 商品价格 商品产地

id  c   编号相同  下单时间 商品信息 3 商品价格 商品产地

如果order中无需写入商品价格 商品产地 下单时间与goods表重复

3.数据表每个字段与当前表的主键产生直接关联(非间接关联)

userid  name height weight orderid 编号 订单时间

评析:编号 订单时间是与此表不是直接关联的

优化:

设计三张表

表1:userid  name height weight

表2:userid   orderid

表3:orderid 编号 订单时间

例1 一个逆范式的例子

商品表Goods1与分类表Category1

Goods1:id      name     cat_id       price

            101     海尔冰箱   2003   6000

分析:

建表

create table Goods1(

id int(11) not null primary key auto_increment,

name varchar(33) not null,

 cat_id  int(11) not null,

 price   mediumint unsigned not null 


)engine =innodb charset=utf8;



Category  cat_id    name  

                  2003      手机

create table Category1(


name varchar(33) not null,

cat_id int(11) not null


)engine =innodb charset=utf8;


需求:

计算每个分类下商品数量是多少?
select c.cat_id,c.name,count(c.*) from category1 as c left join goods1 as  g on g.cat_id=c.cat_id;


上表sql语句是一个多表查询,并且还有count的聚合计算

如果这样的需求很多,类似sql语句查询速度没有优势,

如果需要查询速度的提高,最好设置单表查询,并且没有聚合计算

解决方法:

给Category表增加一个商品数量的字段goods_num

优化后sql语句

select cat_id,name,goods_num from category

但是需要维护额外的工作:

goods商品增加,减少数据都需要维护goods_num字段的信息

增加一个字段做聚合计算获得。


今天看啥 - 高品质阅读平台
本文地址:http://www.jintiankansha.me/t/aoPGAKDLpN
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/28109
 
271 次点击