【问题标题】:The reference of the foreign key says the table doesn't exist外键的引用说表不存在
【发布时间】:2021-05-14 17:04:49
【问题描述】:

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

我该怎么办?

请注意,在数据库中,这三个表位于 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)
)

【问题讨论】:

  • 这不是mysql问题
  • 你使用 SQL Server aka MS SQL,而不是 MySQL
  • 试试 dbo.forum1dbo.user1
  • 您必须收到另一条错误消息。 dbfiddle.uk/…PS。显示的错误消息文本不是由 SQL Server 生成的...
  • creatdata image 不不不不!该数据类型已被弃用近 20 年。使用 varbinary。

标签: sql sql-server ssms


【解决方案1】:

问题是你中间的外键引用

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)
);

您正在将主键(中间)引用到当前表的另一个非唯一列

【讨论】:

  • 很确定Foreign Key (mid) references message1(parentMsgId) 应该是相反的,即Foreign Key (parentMsgId) references message1(mid)
【解决方案2】:

您要做的是尝试将自引用外键添加到表中。您正试图通过引用称为自引用外键的同一个表来使您的主键成为外键。如果您的引用列是唯一的,您应该可以这样做,因为您的引用列 (mid) 是主键,并且默认情况下它是唯一的且不为空。

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)

)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 2023-01-25
    • 2011-09-06
    • 2017-03-16
    相关资源
    最近更新 更多