错误代码:1822。无法添加外键约束。引用表“ resident”中约束“ officials_ibfk_1”的缺少索引
我创建了一个具有两个相互关联的子类表的超类表。为什么会发生此错误?我不能为不是主表的表分配外键吗?
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)
);
答案 0 :(得分:2)
在MySQL中,不必一定要引用的键是主键,但必须通过索引确保它是唯一的(请参见MySQL documentation on foreign key constraints):
MySQL要求在外键和引用的键上建立索引,以便可以快速进行外键检查,而无需进行表扫描。
您收到的错误消息中也清楚地表明了这一点:
无法添加外键约束。 缺少索引在参考表“ resident”中的约束“ officials_ibfk_1”
要解决此问题,请更改:
`residentid` int NOT NULL,
收件人:
`residentid` int NOT NULL UNIQUE,
答案 1 :(得分:1)
FOREIGN KEY是用于将两个表链接在一起的键。
FOREIGN KEY是一个表中的一个字段(或字段的集合),它引用另一张表中的PRIMARY KEY 。 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));