简体   繁体   English

如何防止主串行主键被不按顺序更新的数字?

[英]How to prevent primary serial primary key from being updated with number not in sequence?

CREATE TABLE u_account (
Jid serial primary key,
score int4
);

The primary key works fine (updates itself) ok when I update it like this; 当我这样更新主键时,主键可以正常工作(自行更新);

INSERT INTO u_account ('score') VALUES ('122233344');

However when I insert a value like this; 但是,当我插入这样的值时;

INSERT INTO u_account VALUES ('122233344');

This updates the primary key; 这将更新主键;

I don't want the primary key to accept anything other than the number that is supposed to be coming next. 我不希望主键接受除了应该发送的数字以外的任何东西。

Someone had set it up for me before so that if I put in this code; 以前有人为我设置了它,以便我输入此代码;

INSERT INTO u_account VALUES ('122233344');

it would ignore the primary key and just update score. 它会忽略主键,而只是更新分数。

Please help. 请帮忙。

It looks like you should just reverse the order of the two fields in your table. 看起来您应该只颠倒表中两个字段的顺序。 Then if you INSERT a single column value, it will overwrite the "score" field and use the primary key serial sequence to generate a value for the other column. 然后,如果您插入一个单列值,它将覆盖“分数”字段,并使用主键序列序列为另一列生成一个值。 This example does what I think you want: 这个例子可以满足我的需求:

CREATE TABLE u_account (
score int4,
Jid serial primary key
);

INSERT INTO u_account VALUES ('122233344');

您可以使用“默认”在主键字段中输入正确的值,例如:

INSERT INTO u_account VALUES (DEFAULT, '122233344');

您可以编写一个触发器,以在每次插入时将下一个序列值替换为jid列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM