添加外键约束失败。引用的 table 'informacia' 中缺少约束 'information_ibfk_1' 的索引
Failed to add the foreign key constraint. Missing index for constraint 'information_ibfk_1' in the referenced table 'informacia'
这些表有什么问题?
create table informacia
(
adress_id int primary key,
street varchar(20),
city varchar(10),
state varchar(2),
zip_code int
);
我想为第二个创建外键
create table information
(
FirstName varchar(10) ,
LastName varchar(15),
AdressLine1 varchar(20),
City varchar(10),
StateProvinceCode varchar(2),
PostalCode int,
foreign key(PostalCode)
references informacia(zip_code) on delete set null
);
为了 table 添加外键约束,引用的列(在本例中为 zip_code
)必须是 PRIMARY KEY
或必须具有 UNIQUE
约束(最好使用 NOT NULL
)。
我根据 PostgreSQL 数据库修改了 SQL 语句。你没有提到具体的数据库,PostgreSQL 实现了一个高度标准的 SQL。修改了两处的脚本是:
create table informacia(
adress_id int primary key,
street varchar(20),
city varchar(10),
state varchar(2),
zip_code int not null, -- added NOT NULL
constraint uq_zip_code unique (zip_code) -- added the UNIQUE constranit
);
create table information(
FirstName varchar(10) ,
LastName varchar(15),
AdressLine1 varchar(20),
City varchar(10),
StateProvinceCode varchar(2),
PostalCode int,
foreign key(PostalCode) references informacia(zip_code) on delete set NULL
);
参见 DB Fiddle 中的 运行 示例。
这些表有什么问题?
create table informacia
(
adress_id int primary key,
street varchar(20),
city varchar(10),
state varchar(2),
zip_code int
);
我想为第二个创建外键
create table information
(
FirstName varchar(10) ,
LastName varchar(15),
AdressLine1 varchar(20),
City varchar(10),
StateProvinceCode varchar(2),
PostalCode int,
foreign key(PostalCode)
references informacia(zip_code) on delete set null
);
为了 table 添加外键约束,引用的列(在本例中为 zip_code
)必须是 PRIMARY KEY
或必须具有 UNIQUE
约束(最好使用 NOT NULL
)。
我根据 PostgreSQL 数据库修改了 SQL 语句。你没有提到具体的数据库,PostgreSQL 实现了一个高度标准的 SQL。修改了两处的脚本是:
create table informacia(
adress_id int primary key,
street varchar(20),
city varchar(10),
state varchar(2),
zip_code int not null, -- added NOT NULL
constraint uq_zip_code unique (zip_code) -- added the UNIQUE constranit
);
create table information(
FirstName varchar(10) ,
LastName varchar(15),
AdressLine1 varchar(20),
City varchar(10),
StateProvinceCode varchar(2),
PostalCode int,
foreign key(PostalCode) references informacia(zip_code) on delete set NULL
);
参见 DB Fiddle 中的 运行 示例。