简体   繁体   English

SQL 电子商务数据库。 如何在同一行关联外键?

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

I am trying to create a sql table for orders.我正在尝试为订单创建一个 sql 表。 We have another table what has a primnary key of productID.我们有另一个表,它的主键是 productID。 When a customer creates an order it should list the orderID as well total and a foreignkey of productID.当客户创建订单时,它应该列出 orderID 以及 total 和 productID 的外键。 The issue I have is that it only allows 1 productID.我遇到的问题是它只允许 1 个产品 ID。

Is there a way for sql to add multiple foreign keys to the same row for the same item? sql 有没有办法将多个外键添加到同一行的同一项目? 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.您的表结构每个订单只允许一个产品,因为您在 orders 表上有一个 productId 列。

To allow multiple products per order, I would create an orderItems table.为了允许每个订单有多个产品,我会创建一个 orderItems 表。 Each orderItem has a different productId, and links back to the orders table via an orderId.每个 orderItem 都有不同的 productId,并通过 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM