w j
w j

Reputation: 43

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.

enter image description here

enter image description here

Upvotes: 0

Views: 272

Answers (1)

roswellcat
roswellcat

Reputation: 46

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

Upvotes: 1

Related Questions