sql外键错误

时间:2011-10-16 21:04:30

标签: sql sql-server-2008 foreign-keys

我想创建这两个表但是我收到一个错误,说明由HOLD的外键引用的SECTION键不是主键。正如在查询中看到的那样,它们是主键。我怎么解决这个问题?

create table SECTION( 
ID integer foreign key references TERM(ID),
CID integer foreign key references COURSE(CID),
SECT integer,
constraint PK_SECTION primary key (ID,CID,SECT),
);

create table HOLD( 
NAME varchar(30) foreign key references INSTRUCTOR(NAME),
ID integer foreign key references SECTION(ID),
CID integer foreign key references SECTION(CID),
SECT integer foreign key references SECTION(SECT),
constraint PK_HOLD primary key (NAME,ID,CID,SECT),
);

2 个答案:

答案 0 :(得分:5)

ID,CID,SECT不是主键,它们一起是一个主键(多个属性)。你必须像这样引用它们:

CONSTRAINT "HOLD_FK01" FOREIGN KEY ("ID", "CID", "SECT")
      REFERENCES "SECTION" ("ID", "CID", "SECT")

答案 1 :(得分:0)

使用此声明        约束PK_SECTION主键(ID,CID,SECT) 您只在主键上和以下语句中进行        ID整数外键引用TERM(ID),        CID整数外键引用COURSE(CID) 你正在尝试制作两个外键,但事情是ID和CID不是主键,那里的组合是主键(ID,CID,SECT)

要解决此问题,您需要创建个人主键ID和CID

create table SECTION( 
ID integer foreign key references TERM(ID),
CID integer foreign key references COURSE(CID),
SECT integer,
constraint PK_SECTION_ID primary key (ID),
constraint PK_SECTION_SECT primary key (SECT),
constraint PK_SECTION_CID primary key (CID)
);

CONSTRAINT“FK”FOREIGN KEY(“ID”,“CID”)       参考文献“SECTION”(“ID”,“CID”)