在 MySQL 数据库中存储投票数据的最有效方法(如 StackOverflow)

发布于 2024-12-22 09:09:56 字数 291 浏览 2 评论 0原文

我正在尝试复制 SE 的投票系统。我网站上的用户应该只能对帖子投票一次,然后他们就会被锁定。我目前有两个表,usersposts

我应该如何存储用户对哪些帖子投票的信息?我正在考虑在 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 uids of users which have voted on it. Another idea would have a column in users with the ids 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 技术交流群。

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

发布评论

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

评论(2

情归归情 2024-12-29 09:09:56

创建另一个表来存储 usersposts 表中的信息:

CREATE TABLE votes (
      user_id INT
    , post_id INT
    , PRIMARY KEY (user_id, post_id)
);

使用这种方法:

<块引用>
<块引用>

我正在考虑在帖子中设置一个列来存储对其进行投票的用户的 uid。另一个想法是在用户中创建一个列,其中包含他/她已投票的帖子的 ID。


除非您将值存储为分隔值(以适合一个单元格)或 JSON,否则您最终将在一篇文章中得到许多行。但是,这从一开始就是一个糟糕的方法。

坚持创建一个新表,其中包含确定“投票”的关系。该表很简单,可以检查一下:

SELECT COUNT(t1.post_id) AS vote_count
FROM votes AS t1
WHERE 
    t1.user_id = SOME_INTEGER
    AND t1.post_id = SOME_INTEGER

Create another table to store information from the users and posts tables:

CREATE TABLE votes (
      user_id INT
    , post_id INT
    , PRIMARY KEY (user_id, post_id)
);

With this approach:

I was thinking of having a column in posts which would store the uids of users which have voted on it. Another idea would have a column in users with the ids of the posts he/she has voted on.

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:

SELECT COUNT(t1.post_id) AS vote_count
FROM votes AS t1
WHERE 
    t1.user_id = SOME_INTEGER
    AND t1.post_id = SOME_INTEGER
纸伞微斜 2024-12-29 09:09:56

对于 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.

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