我不能将外键分配给一个 table 而不是另一个 table 的主键吗?

Can't I assign a foreign key to a table that isn't a primary to another table?

错误代码:1822。添加外键约束失败。引用的 table 'resident'

中缺少约束 'officials_ibfk_1' 的索引

我创建了一个超类 table,它有两个子类 table,它们彼此有关系。为什么会出现这个错误?我不能将外键分配给一个 table 而不是另一个 table 的主键吗?

CREATE TABLE User (
    `userid` int NOT NULL AUTO_INCREMENT,
    `username` varchar(30) NOT NULL UNIQUE,
    `password` varchar(30) NOT NULL,
    `emailaddress` varchar(50) NOT NULL UNIQUE,
    `lastname` varchar(20),
    `firstname` varchar(20),
    `birthday` date,
    `sex` varchar(7) CHECK (sex IN ('Male', 'Female')),
    `address` varchar(100),
    `billingproof` varchar(100),
     PRIMARY KEY (userid)
);

CREATE TABLE Resident (
    `residentid` int NOT NULL,
    `userid` int,
    `groupid` int,
    `accntstatus` VARCHAR(13) CHECK (accntstatus IN ('Approved', 'For Approval', 'Disapproved')),
    `residenttype` VARCHAR(40) CHECK (residenttype IN ('Individual Resource', 'Service Provider', 'Individual Resource and Service Provider')),
    `householdid` INT,
    `elected` boolean,
     FOREIGN KEY (userid) REFERENCES User(userid)
);  

CREATE TABLE Officials (
    `electedid` int NOT NULL,
    `userid` int,
    `position` varchar(15) CHECK (position IN ('Staff', 'Village Officer')),
    `isSystemAdmin` boolean,
    `startDate` date,
    `endDate` date,
    `residentid` int,
    FOREIGN KEY (residentid) REFERENCES Resident(residentid),
    FOREIGN KEY (userid) REFERENCES User(userid)
);

A FOREIGN KEY is a key used to link two tables together.

A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table. source

CREATE TABLE Resident (
`residentid` int NOT NULL,
`userid` int,
`groupid` int,
`accntstatus` VARCHAR(13) CHECK (accntstatus IN ('Approved', 'For Approval', 'Disapproved')),
`residenttype` VARCHAR(40) CHECK (residenttype IN ('Individual Resource', 'Service Provider', 'Individual Resource and Service Provider')),
`householdid` INT,
`elected` boolean,
 PRIMARY KEY (residentid),
 FOREIGN KEY (userid) REFERENCES User(userid));  
  • 您需要将 residentid 设为主键,这样您就可以从 获取外键官员居民

在MySQL中引用的键不一定是主键,但必须通过索引保证唯一(参见MySQL documentation on foreign key constraints):

MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan.

您收到的错误消息中也明确指出了这一点:

Failed to add the foreign key constraint. Missing index for constraint 'officials_ibfk_1' in the referenced table 'resident'

所以要解决它,改变:

`residentid` int NOT NULL,

至:

`residentid` int NOT NULL UNIQUE,