简体   繁体   English

如何为一对多关系开发数据库模式?

[英]How can I develop a database schema for a one to many relationship?

I need to implement a shopping cart. 我需要实现一个购物车。 Let's assume I am selling 20 different items. 我们假设我正在销售20种不同的商品。

I have a couple simple tables: 我有几个简单的表:

Cart
-------
tran_id    first_name    last_name    items
1          John          Doe          1:4:15:16


Item
-------
item_id    name         price
1          Ruby         $1.00
2          Diamond      $2.00
...

Point is, how can I query the cart and display the items in an order not in the 1:4:15:16 format but rather as Ruby, Amethyst, Opal, Silver. 重点是,我如何查询购物车并按照1:4:15:16格式的顺序显示项目,而不是Ruby,Amethyst,Opal,Silver。

Your structure isn't one-to-many or many-to-many, it's just one-to-"blob:of:colon:separated:text". 你的结构不是一对多或多对多,它只是一对一的“blob:of:冒号:分隔:文本”。

A proper many-many relationship usually uses a table to bridge the relationship. 适当的多对多关系通常使用表来桥接关系。 In your particular case, that table is often the "transaction detail" table, while your "cart" table is the "transaction header" table. 在您的特定情况下,该表通常是“交易明细”表,而您的“购物车”表是“交易标题”表。

You would have three tables in this situation: 在这种情况下你会有三个表:

CART (transaction header)
---------------
tran_id NUMBER
first_name VARCHAR(100)
last_name VARCHAR(100)

CART_ITEM (transaction detail)
---------------
tran_id NUMBER
item_id NUMBER
.. other details about this line item (quantity, etc)

ITEM
---------------
item_id NUMBER
name  VARCHAR(100)
price  NUMBER(18,4)

Then, to query this to get what you are looking for, just say: 然后,要查询此内容以获得您要查找的内容,请说:

SELECT h.tran_id, i.name, i.price
  FROM cart h 
INNER JOIN cart_item d ON (h.tran_id = d.tran_id)
INNER JOIN item i ON (d.item_id = i.item_id)
WHERE h.tran_id = 1
ORDER BY i.name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM