外键不是默认值,用于非向量ManyToOne关联

时间:2014-08-13 04:16:22

标签: sql database postgresql constraints

考虑我有一张桌子:

create table product(id int8 not null, ... , primary key (id));

我已经插入了一些记录,所以'产品'不是空的。

然后我需要另一张桌子:

create table order(id int8 not null, ..., primary key (id))

之后我决定在'产品'之间添加连接。和订单实体中的' order'添加:

@NotNull
@ManyToOne
private Product product;

所以在sql中我做了以下:

alter table order add column product int8 not null default (???);
alter table order add constraint FK_order_product foreign key (product) references product;

我应该写什么(???)? 如果我将默认设置为0,那么SQL会抱怨如下: (关键产品(0))不在'产品'表

1 个答案:

答案 0 :(得分:0)

看起来你的order表也不是空的(如果表是空的,它可以正常工作)。在您的情况下,我建议您通过执行

添加字段
alter table order add column product int8 not null default 0;

然后更改order表的每一行,以对product字段中的product表进行正确引用,最后添加Foreign Key约束。

此外,如果您的order表填充了测试数据,您可以在执行脚本之前将其截断,并且在这种情况下您可以使用任何默认值,或者根本不使用它。