SQL - "链接" 2个不同表的2个主键?

时间:2015-03-01 05:10:20

标签: sql

我有这3张桌子:

CREATE TABLE ORDERS
(ORDER_NUM CHAR(5) PRIMARY KEY,
FOREIGN KEY (CUSTOMER_NUM) REFERENCES CUSTOMER,
ORDER_DATE DATE,
CUSTOMER_NUM CHAR(3) );

CREATE TABLE PART
(PART_NUM CHAR(4) PRIMARY KEY,
DESCRIPTION CHAR(15),
ON_HAND DECIMAL(4,0) CHECK (ON_HAND >= 0),
CLASS CHAR(2),
WAREHOUSE CHAR(1),
PRICE DECIMAL(6,2) );

CREATE TABLE ORDER_LINE
(ORDER_NUM CHAR(5),
PART_NUM CHAR(4),
NUM_ORDERED DECIMAL(3,0) CHECK (NUM_ORDERED >= 0),
QUOTED_PRICE DECIMAL(6,2),
PRIMARY KEY (ORDER_NUM, PART_NUM));

如您所见,ORDER_LINE包含2个主键 - ORDER_NUM和PART_NUM,它们应链接到其他表。

将ORDER_NUM链接到ORDERS表中的ORDER_NUM以及将PART_NUM链接到PART表中的PART_NUM的最佳方法是什么?

它会添加:

PRIMARY KEY (ORDER_NUM, PART_NUM),
FOREIGN KEY (ORDER_NUM) REFERENCES ORDERS,
FOREIGN KEY (PART_NUM) REFERENCES PART);

到最后一张桌子?

谢谢!

1 个答案:

答案 0 :(得分:1)

  

如您所见,ORDER_LINE包含2个主键 - ORDER_NUM和   PART_NUM,应链接到其他表格。

ORDER_LINE包含一个主键;该主键由两列组成。

是的,你可以将它添加到ORDER_LINE。

PRIMARY KEY (ORDER_NUM, PART_NUM),
FOREIGN KEY (ORDER_NUM) REFERENCES ORDERS,
FOREIGN KEY (PART_NUM) REFERENCES PART);