是否存在反向“AUTO_INCRMENT”的现有实现?在 PostgreSQL 或 MySQL 中?

发布于 2024-12-28 07:01:13 字数 264 浏览 5 评论 0原文

无需手动执行此操作(如果不存在其他选项,我愿意实现),PostgreSQL 或 MySQL 是否有办法拥有一个自动计数器/字段来递减 增量

由于当前应用程序中的各种原因,最好通过查看最近添加的记录(而不是减去)来知道还可以将多少条目(从数据类型的角度来看)添加到表中数据类型最大值中的最新 ID。

那么,这两个系统是否有“AUTO_DECRMENT”或类似的功能?

Without having to do it manually (which I'm open to implementing if no other options exist), is there a way in either PostgreSQL or MySQL to have an automatic counter/field that decrements instead of increments?

For a variety of reasons in a current application, it would be nice to know how many more entries (from a datatype point of view) can still be added to a table just by looking at the most-recently-added record, rather than subtracting the most recent ID from the max for the datatype.

So, is there an "AUTO_DECREMENT" or similar for either system?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

内心旳酸楚 2025-01-04 07:01:13

您必须在 PostgreSQL 中进行一些手动配置,但您可以配置这样的序列:

create sequence example_seq
 increment by -1
 minvalue 1
 maxvalue 5
 start with 5;

create table example(
example_id int primary key default nextval('example_seq'),
data text not null
);

alter sequence example_seq owned by example.example_id;

我想这相当于使用 serial 列创建表,然后更改自动生成的序列。

现在,如果我插入一些行,我会得到 example_id 从 5 开始倒数的结果。如果我尝试插入超过 5 行,我会得到 nextval:达到序列“example_seq”的最小值 (1)

You have to do a bit of manual configuration in PostgreSQL but you can configure a sequence like that:

create sequence example_seq
 increment by -1
 minvalue 1
 maxvalue 5
 start with 5;

create table example(
example_id int primary key default nextval('example_seq'),
data text not null
);

alter sequence example_seq owned by example.example_id;

I suppose it would be equivalent to create the table with a serial column and then alter the auto-generated sequence.

Now if I insert some rows I get example_id counting down from 5. If I try to insert more than 5 rows, I get nextval: reached minimum value of sequence "example_seq" (1)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文