每个INSERT的表ID的增量值 [英] Increment value of a table ID for each INSERT

查看:165
本文介绍了每个INSERT的表ID的增量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PostgreSQL与我的所有表设置。我目前有一个名为的表格,主键名为 comment_id ,这是一个 VARCHAR 的长度为4。



我有一个表单设置来插入一个新的注释到数据库,但我很困惑,我将如何得到我的Java servlet从它的上一个值来++的comment_id。例如。 0001到0002。

解决方案

您不想为您的id列使用VARCHAR。在postgres中,您可以创建一个序列,然后为每个插入获取该序列的下一个值。



这里是文档



基本上,你做一些像

  CREATE SEQUENCE mysequence START 101 

然后,当您插入时,您会执行类似

  INSERT INTO my_comment values(nextval('mysequence')',这是我的评论'); 


I'm using PostgreSQL with all my tables setup. I currently have a table called comments with a primary key called comment_id which is a VARCHAR of length 4.

I have a form setup to insert a new comment into the database but I'm confused as to how I will get my Java servlet to ++ the comment_id from it's previous value. E.g. 0001 to 0002.

解决方案

You don't want to use a VARCHAR for your id column. In postgres you can create a sequence and then get the next value of that sequence for each insert.

here are the docs

Basically, you do something like

CREATE SEQUENCE mysequence START 101

Then, when you insert you do something like

INSERT INTO my_comment values (nextval('mysequence'), 'this is my comment');

这篇关于每个INSERT的表ID的增量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆