书店的最佳销售数据库结构

时间:2018-02-15 22:54:09

标签: mysql database algorithm performance database-design

我有两个数据库结构:

#1:每本书都是一行:

// sale 
+----+---------+-------------+
| id | book_id | customer_id |
+----+---------+-------------+
| 1  | 5       | 123         |
| 2  | 5       | 123         |
| 3  | 9       | 123         |
| 4  | 4       | 456         |
| 5  | 12      | 456         |
+----+---------+-------------+

#2:有一个数字列:

// sale 
+----+---------+-------------+--------+
| id | book_id | customer_id | number |
+----+---------+-------------+--------+
| 1  | 5       | 123         | 2      |
| 2  | 9       | 123         | 1      |
| 3  | 4       | 456         | 1      |
| 4  | 12      | 456         | 1      |
+----+---------+-------------+--------+

正如你所看到的,第一本书对于每本书都有不同的存在(这对将来的一些想法很有用,即退回的书需要返回日期,或者对多次采购给予一些折扣同一本书或其他什么)。但第二个看起来更优,因为它的行数较少。

无论如何,你的推荐是哪一个?我个人喜欢第一个,我只是担心冗余。有第一个结构冗余吗?

2 个答案:

答案 0 :(得分:0)

在我的想法中,第一个解决方案是正确的。 (,第二个错误

<强>为什么
根据您的解释,每次销售都是一个新的有效对象(或记录),其中包含自己的数据,并且自己的存在< / strong>即可。

正如您所说,每个销售对象(记录)都有book_id,customer_id,sale_date,seller_id(或employee_id),sale_price,sale_discount,sale_description,sale_payment_method等。

只有book_id和customer_id看起来很相似(当同一本书的一个客户两次或更多时)并且绝对不是冗余。

如果将它们合并为第二种解决方案,则在设计其余设计和实现时遇到了很多困难。

对您的设计稍作改进:
您可以拥有两个实体,例如 purchase_invoice purchase_invoice_row ,然后您可以在purchase_invoice_row中获得多个销售额。 (当时销售的任何书籍的数量)。我的意思是用两个实体来管理销售信息会更好。 (不是一个)

答案 1 :(得分:0)

我认为你的第二个模型虽然过于简单,但却是更好的选择。但是,正如我所写,它太简单了。我可能会设计它:

Orders
    order_Id int auto increment primary key
    order_date datetime
    order_customer_id int (fk to customers)
    order_seller_id int (fk to sellers)
    unique index on order_date, order_customer_id and order_seller_id

OrderDetails
    OD_order_detail_id int auto increment primary key
    OD_order_id int (fk to orders)
    OD_item_id int (fk to books) 
    OD_pricePerUnit decimal (this is to support special discounts)
    OD_quantity int
    unique index on od_order_id, od_item_id

现在,对于返回返回和类似的东西,你有另一个表:

Returns
    return_id int auto increment primary key
    return_order_detail_id int (fk to order) 
    return_date datetime
    return_quantity int (the number of items returned)
    return_comment varchar(1000) (you will want to know why it's returned)
    unique index on return_order_detail id, return_date

如果您是Codd狂热分子并希望避免使用代理键,则可以丢失自动增量主键,而是使用唯一索引。但是,这意味着您必须通过所有相关表携带唯一索引中指定的列的值:

Orders
    order_Id int auto increment (just to have a numeric reference)
    order_date datetime
    order_customer_id int (fk to customers)
    order_seller_id int (fk to sellers)
    primary key on order_date, order_customer_id and order_seller_id

OrderDetails
    OD_order_detail_id int auto increment (just to have a numeric reference)
    OD_order_date int (fk to orders)
    OD_order_customer_id int (fk to orders)
    OD_order_seller_id int (fk to orders)
    OD_item_id int (fk to books) 
    OD_pricePerUnit decimal (this is to support special discounts)
    OD_quantity int
    primary key on od_order_id, od_item_id