假设自动递增主键是按时间排序的,这是一个糟糕的设计吗?

发布于 2024-10-17 11:59:51 字数 204 浏览 1 评论 0原文

或者更确切地说,积极的一面大于消极的一面吗?

目标是获得N条最近的记录。

优点:

  1. 不必对created_at列建立索引
  2. 您的ORDER BY将使用聚集索引

缺点:

  1. 您依赖主键的时间排序性质来在开发周期的生命周期中保持真实

想法?

Or rather, do the positives outweigh the negatives?

The goal is to get the N most recent records.

pros:

  1. Don't have to index the created_at column
  2. Your ORDER BY will be using a clustered index

cons:

  1. You're relying on the time ordered nature of the primary key to hold true for the life of the development cycle

Thoughts?

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

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

发布评论

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

评论(3

酒绊 2024-10-24 11:59:51

由于数据库事务的原因,多个会话可能会在不同的时间提交,你会发现它并不总是按时间顺序排列的。

另一个缺点是没有在 created_on 上创建索引,您忘记提及:

  • 您无法按特定日期/时间或范围进行搜索或过滤。

我想这个问题只能根据需求来回答。

Due to database transactions, multiple sessions may commit at different times, you will find that it is not always time ordered.

Another con by not creating a index on created_on you forgot to mention:

  • You cannot search or filter by specific date/time or a range.

I think this question can only be answered depending on the requirements.

深居我梦 2024-10-24 11:59:51

尽管这是常见的做法,但在很多情况下主键变得无序。我自己也经常遇到这个问题。我个人发现最好设置在创建时设置的created_at列。

Although it is common practice, there are a lot of cases where the primary key become unordered. I've often run into this problem myself. I personally find it best to set created_at column that's set at the time of creation.

鱼窥荷 2024-10-24 11:59:51

除非您序列化所有插入,否则可能无法保证自动递增键的顺序是按时间顺序排列的。

如果您使用代理键来确定顺序并从中驱动业务逻辑,那么您也会首先破坏代理键的主要优势。代理应该没有商业意义,因此您可以在数据库维护和模式更改期间轻松更新/重新分配值。

Unless you serialize all your inserts there is probably no way to guarantee that the order of the auto-incrementing key is chronological.

If you use a surrogate key to determine the sequence and drive business logic from it then you also undermine the principal advantage of having a surrogate key in the first place. The surrogate is supposed to have no business meaning, so that for example that you can easily update/reallocate the values during database maintenance and schema changes.

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