在数据库中使用布尔标志指定条目的最佳实践是什么?

发布于 2025-01-31 14:41:52 字数 163 浏览 2 评论 0原文

假设我们有一个称为学生的集合(或表格),在我们的系统中,我们需要坚持有史以来最好的学生,这将是我们拥有的所有学生中只有一个。 我想到的第一件事是在学生班上添加IsbestStudent属性(FLAG),但是考虑到这一点,我认为为一百万学生添加一个新的领域是天真的,只是为了使价值真实。 满足这一要求是什么好习惯?

Let's assume that we have a collection (or table) that is called students, and in our system, we need to persist the best student of all time, which is going to be one and only one among all the students we have.
The first thing that came to my mind was to add IsBestStudent property (flag) to the Student class, but thinking about it I think it is naive to add a new field say for one million students just to have one with the value true.
What would be a good practice to fulfill this requirement?

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

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

发布评论

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

评论(1

一直在等你来 2025-02-07 14:41:52

一个简单的解决方案是创建另一个表:

CREATE TABLE BestStudent (
  student_id BIGINT PRIMARY KEY,
  FOREIGN KEY (student_id) REFERENCES Student(student_id)
);

此表只有一个行,因此必须仅引用一个学生。您不需要student表中的新列,您只需要该表即可具有该小表的主键。

如果您真的只想保留单身最好的学生,那么您绝对不应该再插入更多的行。如果新学生击败了前最佳学生的表现,则更新当前的行。

您可能还需要使用此表来存储最好的学生的历史,在这种情况下,您将保留多行。由你决定。但是关键是您可以使用此技术避免在学生表中的数百万行中添加一列。这张桌子一定会保持很小。

A simple solution is to create another table:

CREATE TABLE BestStudent (
  student_id BIGINT PRIMARY KEY,
  FOREIGN KEY (student_id) REFERENCES Student(student_id)
);

This table has just one row, so it must reference only one student. You don't need a new column in the Student table, you only need that table to have a primary key for this little table to reference.

If you really only want to keep the single best student, then you should simply never insert any more rows. Update the current row if a new student beats the former best student's performance.

You might also want to use this table to store a history of the best students, in which case you would keep multiple rows. It's up to you. But the point is that you can use this technique to avoid adding a column to millions of rows in the student table. This table is bound to stay small.

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