mysql - 如何标准化/分解包含多个重复选项字段的表

标签 mysql normalization database-normalization

假设我有一张来自不同供应商的电机表,以及电机成本和选项成本,以及特定电机中是否存在特定选项。

如何在 SQL (MySQL) 中最好地构建它?

示例表:

motor
------------ 
id
model
listprice
price
cost_base //base cost of motor
position
weight
option_1_present //does option1 exist on the motor?
option_1_cost    //cost of option1 if it is selected by the user
option_2_present
option_2_cost
option_3_present
option_3_cost
option_4_present
option_4_cost
option_5_present
option_5_cost
option_6_present
option_6_cost

除了标准化之外,我很好奇是否应该根据“成本”和“存在”因素将字段分解为单独的表。

到目前为止,这个设计对我来说是有效的,即根据客户偏好(即选项 1、3),我将研究 DB 以选择具有这些选项的电机,然后给出价格

这么说SELECT * from motor where option_1_present=1 and option_3_present=1 然后将成本相加。

问题

是否有任何规范化/分解任务需要使用此表完成?

最佳答案

您违反了数据库设计的基本规则。您没有确认第一范式 1NF。

As per First Normal Form, no two Rows of data must contain repeating group of information i.e each set of column must have a unique value, such that multiple columns cannot be used to fetch the same row. Each table should be organized into rows, and each row should have a primary key that distinguishes it as unique.

Database Normalization

相反,您应该将选项的存在分解(特别是因为您已经表明可能添加了选项)到存在表中,并在存在和电机之间添加一个桥接表。

motor
------------ 
id
model
listprice
price
cost_base //base cost of motor
position
weight

bridge
--------
bridgeid
motorid
presenceid

presence
------------ 
presenceid
option
cost

这样,您的存在选项就不会在电机表中重复成本等。如果您想添加另一个选项,则不需要锁定来重建大型表,因为在任何给定时间,存在表中仅包含一些记录。桥接表会告诉您对于用户指定的哪些电机有哪些选项。基本上将所有数据从水平变为垂直。您的查询必须变得更复杂一些,但这是一种更简洁、更可扩展的方法。

关于mysql - 如何标准化/分解包含多个重复选项字段的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31574099/

相关文章:

java - mysql 数据类型 SET 的 Hibernate 注释

mysql - 2NF 数据库规范化

python - 在 Keras 中规范化神经网络的验证集

database - 数据库关系不在 BCNF 中的最小证据是什么?

mysql - 我必须建立这种关系吗?

只有 id 和描述的表的数据库规范化

mysql - 使用 MySQL 驱动程序问题交叉编译 Qt5 (Mingw)

mysql - 如何通过两个 IN 变量进行排序

PHP 注册时出错

SQL Server 规范化策略 : varchar vs int Identity