在 MySQL 数据库中存储投票数据的最有效方法(如 StackOverflow)
我正在尝试复制 SE 的投票系统。我网站上的用户应该只能对帖子投票一次,然后他们就会被锁定。我目前有两个表,users
和 posts
。
我应该如何存储用户对哪些帖子投票的信息?我正在考虑在 posts
中创建一个列来存储对其进行投票的用户的 uid
。另一个想法是在 users
中有一列,其中包含他/她投票的帖子的 id
。
我该怎么做?我想考虑可扩展性并易于确定投票是否有效。
I'm trying to replicate SE's voting system. User's on my website should only be able to vote on posts one time, then they are locked in. I currently have two tables, users
and posts
.
How should I store information on which posts a user has voted on? I was thinking of having a column in posts
which would store the uid
s of users which have voted on it. Another idea would have a column in users
with the id
s of the posts he/she has voted on.
How should I do this? I want to take scalability into account and easy of determining whether or not the vote is valid.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
创建另一个表来存储
users
和posts
表中的信息:使用这种方法:
除非您将值存储为分隔值(以适合一个单元格)或 JSON,否则您最终将在一篇文章中得到许多行。但是,这从一开始就是一个糟糕的方法。
坚持创建一个新表,其中包含确定“投票”的关系。该表很简单,可以检查一下:
Create another table to store information from the
users
andposts
tables:With this approach:
Unless you store the values as delimited values (to fit in one cell) or JSON, you'll end up with many rows for just one post. But then, that's a bad approach to start with.
Stick with creating a new table which contains the relationship determining "voting". The table is simple enough to check:
对于 stackoverflow 这么大的东西,最佳实践是将各个投票存储在单独的表中。但也要在直接附加到帖子的字段中保留派生的投票计数。随着数据库规模的增长,汇总每次查看帖子的所有投票将变得异常昂贵。
通过使用此用户/投票表上的触发器,保留此派生字段相对容易。
Best practice, for something the size of stackoverflow, is to store the individual votes in a separate table. But also keep a derived vote count in a field directly attached to the post. As database sizes grow, it'll become prohibitively expensive to sum up all the votes on every viewing of a post.
Keeping this derived field is relatively easy by use of triggers on this user/votes table.