外键的引用说 table 不存在

The reference of the foreign key says the table doesn't exist

我创建了 3 个 table,即使所有三个 table 都存在并且列具有相同的类型,它仍然说“引用的 table 无效”。

我该怎么办?

请注意,在数据库中,三个 table 位于 3 个单独的 SQL 文件中。

CREATE TABLE user1(
    uid int identity ,
    primary key (uid),
    uname nvarchar(30) not null
)
CREATE TABLE forum1 (
    fname int identity ,
    primary key (fname),
    topic nvarchar(50) not null ,
    creatdata image  
)
CREATE TABLE message1(
    mid int not null ,
    Primary Key (mid),
    parentMsgId int not null,
    title nvarchar (50) not null,
    body nvarchar(50) not null,
    createData image not null,
    fname int ,
    creatorId int not null,
    Foreign Key (fname) references forum1(fname),
    Foreign Key (creatorId) references user1(uid),
    Foreign Key (mid) references message1(parentMsgId)
)

问题是你在中间引用了外键

CREATE TABLE user1(
    uid int identity ,
    primary key (uid),
    uname nvarchar(30) not null
);
CREATE TABLE forum1 (
    fname int identity ,
    primary key (fname),
    topic nvarchar(50) not null ,
    creatdata image  
);
CREATE TABLE message1(
    mid int not null ,
    parentMsgId int unique,
    title nvarchar (50) not null,
    body nvarchar(50) not null,
    createData image not null,
    fname int ,
    creatorId int not null,
    primary key (mid),
    Foreign Key (fname) references forum1(fname),
    Foreign Key (creatorId) references user1(uid),
    Foreign Key (mid) references message1(parentMsgId)
);

您正在引用当前表的主键 (mid) 另一个不唯一的列

您尝试做的是尝试将自引用外键添加到 table。您正试图通过引用相同的 table 来使您的主键成为外键,这被称为自引用外键。如果您引用的列是唯一的,您应该能够执行此操作,因为您的引用列 (mid) 是主键,并且默认情况下它是唯一的而不是 null。

CREATE TABLE message1(
   mid int not null primary key ,   
   parentMsgId int not null unique,
   title nvarchar (50) not null,
   body nvarchar(50) not null,
   createData image not null,
   fname int ,
   creatorId int not null,
   Foreign Key (fname) references forum1(fname),
   Foreign Key (creatorId) references user1(uid),
   Foreign Key (mid) references message1(parentMsgId)

)

您可以在 table 中使用自引用外键。有这样的限制。这些列应该具有相同的数据类型。试试这个代码并检查可能性