小学和初级外键约束混淆

时间:2014-03-04 19:16:42

标签: sql oracle constraints

目前正在尝试将外键应用于我创建的表,但我收到了SQL错误:

SQL Error: ORA-02270: no matching unique or primary key for this column-list
02270. 00000 -  "no matching unique or primary key for this column-list"
*Cause:    A REFERENCES clause in a CREATE/ALTER TABLE statement
       gives a column-list for which there is no matching unique or primary
       key constraint in the referenced table.
*Action:   Find the correct column names using the ALL_CONS_COLUMNS
       catalog view

我在这里离开的地方有很大的损失,我认为每个人都有秩序,但我不能指出什么是错的。

以下是我正在使用的相关创建和更改脚本,如果有人可以指出我出错的地方:

创造结果& DopingTest:

CREATE TABLE Results
(
RaceID NUMBER,
HorseID NUMBER,
JockeyID NUMBER,
Position numeric(2)
);

CREATE TABLE DopingTest
(
RaceID NUMBER,
HorseID NUMBER,
TakenBy varchar2(60)
);

添加约束:

ALTER TABLE Results
ADD(
  CONSTRAINT pk_ResultsID
    PRIMARY KEY (RaceID,HorseID));

ALTER TABLE DopingTest
ADD(
  CONSTRAINT pk_DopingTest
    PRIMARY KEY (RaceID, HorseID));

ALTER TABLE Results
ADD(
  CONSTRAINT fk_raceID
    FOREIGN KEY (RaceID)
    REFERENCES Race(RaceID),
  CONSTRAINT fk_horseID
    FOREIGN KEY (HorseID)
    REFERENCES Horse(HorseID),
  CONSTRAINT fk_JockeyID
    FOREIGN KEY (JockeyID)
    REFERENCES Jockey(JockeyID));

ALTER TABLE DopingTest
ADD(
  CONSTRAINT fk_RaceIDDT
    FOREIGN KEY (RaceID)
    REFERENCES Results(RaceID),
  CONSTRAINT fk_HorseIDDT
    FOREIGN KEY (HorseID)
    REFERENCES Results(HorseID));

非常感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:5)

如果results具有复合主键,则外键必须引用该键的两个组件。

ALTER TABLE DopingTest
ADD(
  CONSTRAINT fk_RaceIDDT
    FOREIGN KEY (RaceID, HorseID)
    REFERENCES Results(RaceID, HorseID)
);