SQL 在表上插入或更新违反外键约束

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2444899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 05:40:55  来源:igfitidea点击:

insert or update on table violates foreign key constraint

sqldatabasepostgresql

提问by suprasad

I have two tables: entitytypeand project. Here are the create table statements:

我有两个表:entitytypeproject。以下是创建表语句:

Create table project ( 
pname varchar(20) not null, 
primary key(pname)
);

create table entitytype( 
entityname varchar(20) not null, 
toppos char(100), 
leftpos char(100), 
pname varchar(20) not null, 
primary key(entityname), 
foreign key(pname) references project(pname) on delete cascade on update cascade
);

When I try to insert any values into the entitytypetable, I get the following error:

当我尝试将任何值插入到entitytype表中时,出现以下错误:

ERROR: insert or update on table "entitytype" violates foreign key constraint "entitytype_pname_fkey"
  Detail: Key (pname)=(494) is not present in table "project".

Can anyone shed some light on what I am doing wrong?

任何人都可以阐明我做错了什么吗?

回答by Mitch Wheat

The error message means you are attempting to add an entityType that does not have a corresponding Project entry. (I don't know your domain or what you are trying to achieve, but that schema design looks wrong to me...)

该错误消息意味着您正在尝试添加没有相应项目条目的 entityType。(我不知道您的领域或您想要实现的目标,但该架构设计在我看来是错误的...)

回答by Larry Lustig

Do you not have a record in table project with a pname of (in your example) 494?

您在表项目中没有 pname 为(在您的示例中)494 的记录吗?

The key relationship says no pname is allowed in the entity table unless it matches a pname in the project table.

键关系表示实体表中不允许有 pname,除非它与项目表中的 pname 匹配。