简体   繁体   English

SQL多个外键指向同一主键

[英]SQL Multiple foreign keys pointing to same primary key

Is there going to be a problem with my following design? 我的以下设计会出现问题吗? Basically, I want keep track of a total payment by a customer (eg. $50) that is split between two items (eg. $20 and $30). 基本上,我希望跟踪客户的总付款(例如,50美元),该付款分为两个项目(例如,20美元和30美元)。 But I want to be able to look at any item - ITEM(ITEM_ID) and know how much the customer spent on their total bill - PAYMENT(PAYMENT_AMOUNT). 但我希望能够查看任何项目 - ITEM(ITEM_ID)并了解客户在其账单上花费了多少 - 付款(PAYMENT_AMOUNT)。 To keep it simple I included minimal columns: 为了简单起见,我包含了最少的列:

CREATE TABLE ITEM (
  ITEM_ID           NUMBER(7,0)         NOT NULL,
  ITEM_SALE_AMT     NUMBER(7,2)         NOT NULL,
  PAYMENT_ID        NUMBER(7,0)         NOT NULL,
  PRIMARY KEY (ITEM_ID),
  FOREIGN KEY (PAYMENT_ID) REFERENCES PAYMENT(PAYMENT_ID)
);

CREATE TABLE PAYMENT (
  PAYMENT_ID        NUMBER(7,0)         NOT NULL,
  PAYMENT_AMOUNT    NUMBER(7,2)         NOT NULL,
  ITEM_1            NUMBER(7,0)         ,
  ITEM_2            NUMBER(7,0)         ,
  PRIMARY KEY (PAYMENT_ID),
  FOREIGN KEY (ITEM_1) REFERENCES ITEM(ITEM_ID),
  FOREIGN KEY (ITEM_2) REFERENCES ITEM(ITEM_ID)
);

Firstly, each item is unique (so you can't have two payments for the same item). 首先,每个项目都是唯一的(因此您不能为同一项目支付两笔款项)。 Obviously, if the customer pays for many items in one transaction, my PAYMENT table will have a lot of columns (but this has never happened in 30 years, usually 1 and occasionally 2 or 3). 显然,如果客户在一次交易中支付了很多项目,我的PAYMENT表格将有很多列(但这在30年内从未发生过,通常是1年,有时候是2或3年)。

Is there a major flaw I am not seeing or could this be improved? 是否有一个我没有看到的重大缺陷或者可以改进?

This is a simple one-to-many relationship. 这是一个简单的一对多关系。 You should take out the ITEM_1 and ITEM_2 columns and associated foreign keys in the PAYMENT table. 您应该从PAYMENT表中取出ITEM_1和ITEM_2列以及相关的外键。 The items are all linked to their payments via the foreign key in the ITEM table. 这些项目都通过ITEM表中的外键与其付款相关联。 That's all you need. 这就是你所需要的。

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

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