无法创建 table。 SQL 错误 02270

Cannot create table. SQL Error 02270

这是我要创建的 table。但是,我收到错误

SQL Error: ORA-02270: no matching unique or primary key for this column-list

SQL:

create table Meets_In
(
    cid char(20),
    rno integer,
    time char(20),
    CONSTRAINT PRIM_KEY PRIMARY KEY(time),
    constraint meets_fk1 foreign key(cid) references COURSES(CID),
    constraint meets_fk2 foreign key(rno) references ROOMS(RNO)
); 

这些是父 table:

create table Courses
(
    cid char(20),
    cname char(20),
    credits integer,
    constraint CoursesKey Primary Key (cid, cname)
);

CREATE TABLE ROOMS 
(
    rno INTEGER,
    address CHAR(20),
    capacity INTEGER,
    CONSTRAINT room_key PRIMARY KEY(rno)
);

我不明白为什么会出现此错误。

Meets_In 充当关联词 table。因此它的主键应该包括外键到它正在关联的table中。

尝试使用包含以下内容的主键:cidcnamernotime

正如其他人所指出的,courses 的主键是 (cid, cname),因此您还需要将这两个都包含在外键约束 meets_fk1 中。或者,如果可能,请确保 cid 仅是 courses.

上的主键

(我觉得time可能是一个保留字,或许可以考虑重命名。)

Cause

如错误消息所示,ORA-2270 在存在 no matching unique or primary key for this column-list 时发生。这可能是因为

  • parent 完全没有约束
  • parenttable的约束是一个复合键,我们没有引用外键语句中的所有列。

现在在你的 COURSES table 中,CID 不是 primary key。它是 cid,cname 的组合。所以对于每个 cid,可以有多个行。

现在,当您引用 cid 作为 meets_in 的外键时,它将不起作用,因为它违反了我上面提到的第二点。

Workaround

meets_in table 中也添加列 cname。然后像下面这样使用它。

create table Meets_In
(
    cid char(20) not null,
        cname char(20),
    rno integer not null,
    time1 char(20) not null,
    CONSTRAINT PRIM_KEY PRIMARY KEY(time1),
    constraint meets_fk1 foreign key(cid,cname) references COURSES (cid,cname), /*Added cid,cname */
    constraint meets_fk2 foreign key(rno) references ROOMS (RNO)
);