如何使用外键作为主键

时间:2011-09-16 08:29:14

标签: sql-server-2008 foreign-keys relational-database foreign-key-relationship composite-key

我有一个带有两个外键的表作为复合键。

ActivityTbl -

(activityNbr(PK), supervisor(FK), status, type, startDate, endDate, location )

VolunteerTbl -

(volunteerNbr(PK), name, address, contact)

现在我创建了一个表格,志愿者的选择可以根据他们的优惠等级进行存储。

ActivityChoice

(activityNbr(FK), VolunteerNbr(FK), Rating)

因此,这2个FK的组合构成了一个复合键。我正在使用sql Server来创建表。

Create ActivityChoiceTbl(
     VolunteerNbr   int NOT NULL,
     ActivityNbr    int NOT NULL,
     Rank           int NOT NULL,
     CONSTRAINT PKActivityChoice    PRIMARY KEY (VolunteerNbr,ActivityNbr), 
     CONSTRAINT CKRank CHECK (Rank>0 AND Rank<=9));

所以在这种情况下我是否需要添加另一个外键约束来提及它们是外键?我做得对吗?感谢

2 个答案:

答案 0 :(得分:2)

是的,您需要两个外键约束。标准SQL中最直接的方法是立即引用该表。

Create ActivityChoiceTbl(
     VolunteerNbr   int NOT NULL REFERENCES VolunteerTbl (volunteerNbr),
     ActivityNbr    int NOT NULL REFERENCES ActivityTbl (activityNbr),
     Rank           int NOT NULL,
     CONSTRAINT PKActivityChoice    PRIMARY KEY (VolunteerNbr,ActivityNbr), 
     CONSTRAINT CKRank CHECK (Rank>0 AND Rank<=9));

但是添加两个约束子句可以让你命名约束,这是一种更好的做法。

Create ActivityChoiceTbl(
     VolunteerNbr   int NOT NULL,
     ActivityNbr    int NOT NULL,
     Rank           int NOT NULL,
     CONSTRAINT PKActivityChoice    PRIMARY KEY (VolunteerNbr,ActivityNbr), 
     CONSTRAINT FKActivityChoiceVolunteerNbr 
         FOREIGN KEY (VolunteerNbr) REFERENCES VolunteerTbl (VolunteerNbr),
     CONSTRAINT FKActivityChoiceActivityNbr 
         FOREIGN KEY (ActivityNbr) REFERENCES ActivityTbl (ActivityNbr),
     CONSTRAINT CKRank CHECK (Rank>0 AND Rank<=9));

如果ActivityChoice是一个需要引用ActivityChoiceTbl的单独表,那么你还需要这些内容。

CREATE TABLE ActivityChoice (
    VolunteerNbr INTEGER NOT NULL,
    ActivityNbr INTEGER NOT NULL,
    Rating  DECIMAL (2,1) NOT NULL CHECK (Rating between 0 and 9),  -- Pure guess
    PRIMARY KEY (VolunteerNbr, ActivityNbr),
    FOREIGN KEY (VolunteerNbr, ActivityNbr) 
      REFERENCES ActivityChoiceTbl (VolunteerNbr, ActivityNbr)
);

答案 1 :(得分:0)

我建议你在ActivityChoice表中有一个单独的PrimaryKey。创建VolunteerNbr和ActivityNbr外键,并为两列VolunteerNbr,ActivityNbr添加复合唯一键约束。

您想要了解一些关于复合外键的观点。 http://www.upsizing.co.uk/Art10_MultiPartkeys.aspx

http://social.msdn.microsoft.com/Forums/en/transactsql/thread/158d77f7-3029-43bc-bba6-a8a12374f00c