简体   繁体   中英

Database design issue in project?

I am designing a database for my app. In which I want to do mapping between multiple tables. Now situation is like There is one user table. User can have generate multiple orders. So I was thinking if I can put json obejct of order_id in a column in order table. Or I can create a user_id column in order table & repeat user_id for same user. So which is a better way of doing it?

PS: What is the standard way of doing it?

A user can place multiple orders.

Based on this you should maintain three different tables as given below:

  • User (user_id,...)
  • Order (order_id,...)
  • UserOrder (user_id,order_id,...)

Only the primary keys in the above tables are focused

Storing comma separated list or json object will worsen the design. And this is strongly discouraged.

EDIT:

As @NevilleK suggested, the above design is typically used for many-to-many relationships. For one-to-many relationship you can create a foreign key constraint in orders table where user_id should refer to the user_id in the User table.

But still you can adopt the above design for one-to-many relationship since many-to-many qualifies for one-to-many too.

您应该在订单表中只包含user_id ,然后进行类似的查询

select * from orders where user_id = *some_user_id*

A user can place multiple orders which in turn can have multiple line items. Each line item can have n quantity of a specific product. So when product comes in picture, then it becomes many to many relationship between user and product because a user can place order for many products and a product can be ordered by many users. So my suggestion is -

  1. Create a User table with UserID
  2. Create a PurchaseOrder table with OrderID, UserID and LineItemID
  3. Create a LineItem table with OrderID, ProductID and LineItemID
  4. Create a SKU table with ProductID

The best way is to have different table for your

  1. User table - which hosts the user information
  2. Transaction table - which will have order_id against each user_id.

Transaction table will carry all the transaction details with user_id. If you create a JSON object, how will you map the USER to the transaction. So at the time of retrieving the json information you will have to map it to the user table anyway. I suggest you the use the above said method, which will help you maintain and scale your application much easily.

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