简体   繁体   中英

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.

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.

Your structure isn't one-to-many or many-to-many, it's just one-to-"blob:of:colon:separated:text".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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