创建了两个表,即Address和Employee。具有关系的employee有n个地址。 DB脚本如下。
create table address(addressid int,city varchar(10),pincode varchar(10));
insert into address(addressid,city,pincode) values(201,'Hosur',635109);
create table employee(empid int , firstname varchar(20),lastname varchar(20),department varchar(10),emailAddress varchar(50),baseLocation varchar(20),address int,FOREIGN KEY (Address) REFERENCES Address(addressId));
但是在尝试创建员工表时出现以下错误:
Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'employee_ibfk_1' in the referenced table 'Address' 0.117 sec
最佳答案
您可能应该在地址表中的地址 ID 上添加主键,这将创建所需的索引。在您当前的脚本中,不能保证 addressid 是唯一的,因此,如果存在重复项,外键永远无法确定要引用哪一行。
create table address(addressId int primary key not null, city varchar(10), pincode varchar(10));
关于java - 错误代码 : 1822. 添加外键约束失败。引用表 'employee_ibfk_1' 中缺少约束 'Address' 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55759582/