【问题标题】:SQL Error, unable to create table on a certain formatSQL 错误,无法创建特定格式的表
【发布时间】:2020-02-20 11:10:54
【问题描述】:

在以下两个语句之间创建表时遇到错误

CREATE TABLE SECTION (
cid     varchar(10)     not null,
sno     varchar(3)      not null,
primary key (cid, sno),
foreign key (cid) references COURSE (cid)
);

CREATE TABLE ROUND_RELEASE (
cid     varchar(10)     not null,
sno     varchar(3)      not null, 
rid     int         not null,
foreign key (cid) references SECTION (cid),
foreign key (sno) references SECTION (sno),
foreign key (rid) references ROUND   (rid)
);

错误代码:1822。添加外键约束失败。引用表“section”中的约束“round_release_ibfk_2”缺少索引

但是,当我尝试交换 SECTION 表中的主键顺序时,我能够毫无错误地创建两个表

CREATE TABLE SECTION (
cid     varchar(10)     not null,
sno     varchar(3)      not null,
primary key (**sno, cid**),
foreign key (cid) references COURSE (cid)
);

CREATE TABLE ROUND_RELEASE (
cid     varchar(10)     not null,
sno     varchar(3)      not null, 
rid     int         not null,
foreign key (cid) references SECTION (cid),
foreign key (sno) references SECTION (sno),
foreign key (rid) references ROUND   (rid)
);

上面的代码有效,我只是交换属性,据我所知,顺序无关紧要,所以我很困惑为什么会发生这种情况。

对此有任何指导吗?谢谢!

【问题讨论】:

    标签: mysql sql foreign-keys create-table


    【解决方案1】:

    根据错误信息,我假设您使用的是 MySQL。

    你看到的是documented behavior

    在被引用的表中,必须有一个索引,其中被引用的列是相同顺序的first列。

    不过,让我指出,您的代码可能并没有达到您真正想要的效果。您可能应该创建一个复合外键,它引用列的元组,而不是每列一个外键:

    create table round_release (
        cid varchar(10) not null,
        sno varchar(3)  not null, 
        rid int not null,
        foreign key (cid, sno) references section(cid, sno),
        foreign key (rid) references round(rid)
    );
    

    最后要注意的是您的round_release 表没有定义主键;这不是一个好的做法,将来可能会以多种方式伤害您。因此,请务必为表创建一个主键,或者作为单独的列(可能是自动递增的),或者作为现有列的组合。

    【讨论】:

    • 据我所见,没有一个名为round的表(如外键(rid)引用round(rid))。
    • @P.Salmon:我只能想象round 表存在,但 OP 没有显示它。否则,OP 所说的第二个脚本工作正常,会出错......
    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多