赞成票和反对票投票系统的数据库结构

发布于 2024-10-07 02:11:33 字数 295 浏览 1 评论 0原文

我将为 Web 应用程序创建一个投票系统,并想知道将投票存储在 (SQL) 数据库中的最佳方法是什么。

投票系统与 StackOverflow 的投票系统类似。我现在正在考虑是否应该将赞成票和反对票存储在不同的表中。这样就可以更轻松地计算所有选票。反对票。另一方面,我必须查询两个表来查找用户或投票项目的所有投票。

另一种选择是一个带有布尔字段的表,该字段指定此投票是赞成票还是反对票。但我想向上或向下计数选票是相当慢的(当你有很多选票时),并且布尔字段上的索引(据我所知)没有多大意义。

您将如何创建数据库结构?一桌还是二桌?

I am going to create a voting system for a web application and wonder what the best way would be to store the votes in the (SQL) database.

The voting system is similiar to the one of StackOverflow. I am pondering now if I should store the up and down votes in different tables. That way it is easier to count all up votes resp. down votes. On the other hand I have to query two tables to find all votes for an user or voted item.

An alternative would be one table with a boolean field that specifies if this vote is an up or down vote. But I guess counting up or down votes is quite slow (when you have a lot of votes), and an index on a boolean field (as far as I know) does not make a lot of sense.

How would you create the database structure? One or two tables?

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

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

发布评论

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

评论(4

日记撕了你也走了 2024-10-14 02:11:39

我想,您将需要用户和正在投票的实体之间的链接表。这将允许您查看哪些用户已经投票并阻止他们提交进一步的投票。该表可以用布尔值记录是赞成票还是反对票。

我建议在投票实体中存储当前的投票统计字段以方便查询。如果忽略这一点,则节省的大小可以忽略不计。

You will need a link table between users and the entities which are being voted on, I would have thought. This will allow you to see which users have already voted and prevent them from submitting further votes. The table can record in a boolean whether it is an up or down vote.

I would advise storing in the voted entity a current vote tally field to ease querying. The saving in size would be negligible if you omitted this.

习惯成性 2024-10-14 02:11:38

如果您的投票只是向上/向下,那么您可以创建一个链接到帖子的votes表,并将设置为1或-1(向上/向下)。这样您就可以一次性求和

If your votes are just up/down then you could make a votes table linking to the posts and having a value of 1 or -1 (up / down). This way you can sum in a single go.

生生漫 2024-10-14 02:11:37

关于评论,我们找到了最适合 Zardoz 的解决方案,

他不想总是计票,需要尽可能多的细节尽可能。所以解决方案是两者的混合。

  1. 在所考虑的表中添加一个整数字段来存储投票计数(确保不会溢出)。
  2. 创建额外的表来记录投票(用户、帖子、日期、向上/向下等)。

我建议在日志表中插入/删除/更新投票时使用触发器自动更新“投票计数字段”。

Regarding the comments, we found the solution that best fits to Zardoz

He does not want to always count votes and needs as much details as possible. So the solution is a mix of both.

  1. Adding an integer field in the considered table to store vote counts (make sure there won't be overflows).
  2. Create additional tables to log the votes (user, post, date, up/down, etc.)

I would recommend to use triggers to automatically update the 'vote count field' when inserting/deleting/updating a vote in the log table.

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