简体   繁体   中英

How store order and products in a database?

I have an order with details such customer id, order date, order type etc...

The order then contains a list of products on that order

Do I create one table for the order and then another table for the products?

If so, should there then be foreign keys between the 2 tables?

Your table structure should look like below. In your product table create a reference to order_id in order table by means of foriegn key. Thatway, each order will be associated with one or more products and you can find out the same using a JOIN in your SELECT query.

Table: Order(order_id Primary key,customer id, order date, order type)

Table: Products(product_id primary key, order_id foriegn key,col1, col2); 

Explanation:

A product may not be associated with a order at all time but a order must be associated with a product (Obhious reason, we can't have a blank order).

Here's how I'd model it:

  1. Customer can have many Orders; an Order belongs to one Customer.
  2. An Item refers to one Product
  3. An Order can have many Items; an Item belongs to one Order.

One-to-many foreign keys always belong in the "many" table and refer back to their "one" table.

If you have many to many relationships you need a JOIN table, which has two one-to-many foreign keys.

You current condition may works if the product is not belong to your store/source , you are getting products from different source and client order the product so you can maintain the order with the require details. if the product came from your source/store then you must need the product and order

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