简体   繁体   中英

SQL ecommerce database. how to relate foreign keys in same row?

I am trying to create a sql table for orders. We have another table what has a primnary key of productID. When a customer creates an order it should list the orderID as well total and a foreignkey of productID. The issue I have is that it only allows 1 productID.

Is there a way for sql to add multiple foreign keys to the same row for the same item? If that makes sense?

I placed both tables here to try and show what I meant.

在此处输入图像描述

在此处输入图像描述

Your table structure only allows one product per order, because you've got a single productId column on the orders table.

To allow multiple products per order, I would create an orderItems table. Each orderItem has a different productId, and links back to the orders table via an orderId. Like this:

------------------------
orders table
------------------------
orderId (primary key)
orderDate
orderTotal
customerId (foreign key)
specialInstructions

-------------------------
orderItems table
-------------------------
orderItemId (primary key)
orderId (foreign key)
productId (foreign key)
quantity

-------------------------
products table
-------------------------
productId (primary key)
productTitle
productDescription
productPrice

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