简体   繁体   中英

How to store a list of items in orders table (MySQL)

I've got four tables:

Order [orderId, *itemId, totalPrice]

Item [itemId, *orderId, quantity]

Poster [posterId, *orderId, size, material]

Card [cardId, *orderId, size, text]

Item is essentially an abstract table that holds data relevant to every item. All items (posters and cards) have some unique properties.

Two questions:

  1. Is there a way to set up an inheritance relationship between Items table and poster / card? Such that Order table would only accept itemId of a an Item's child?
  2. An order can have multiple items, so it should hold a list of foreign item keys, rather than just one. How do I tackle that?

You can create a table for Items, and set up foreign key constraint in Poster/Card table to Items table.

Is there a way to set up an inheritance relationship between Items table and poster / card? Such that Order table would only accept itemId of a an Item's child?

Set a foreign key constraint on Order table to Item table.

An order can have multiple items, so it should hold a list of foreign item keys, rather than just one. How do I tackle that?

In aa many to one relationship mapping should be stored on one side ie Item side in your case not Order side. And if Item table is kind of static you should create a mapping table for managing the relationship between Item and Order, and not keep in Order table.

Better you remove itemId and orderId from Order and Item table respectively. Treat them both as Master . As you said an Order can have multiple items , create a third table eg order_item and create two columns orderId & itemId and refer them to the corresponding master_tables

orderId|itemId|
-------+------+--
   1   |   1  |
   1   |   2  |
   1   |   3  |

This way you can have mulitple Items for single Order and you can do the same for other tables

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