优化Mysql以避免冗余但仍能快速访问可计算数据

发布于 2024-09-01 20:00:31 字数 219 浏览 1 评论 0原文

为了解决这个问题,举一个例子:我有一个包含用户、问题和答案的数据库。每个用户都有一个分数,可以使用问题和答案表中的数据来计算。因此,如果我在用户表中有一个分数字段,那么它将是多余的。但是,如果我不使用分数字段,那么每次计算分数都会显着减慢网站速度。

我当前的解决方案是将其放入分数字段中,然后每隔几个小时运行一个 cron 来重新计算每个人的分数并更新该字段。

有更好的方法来处理这个问题吗?

An example for the sake of the question: I have a database which contains users, questions, and answers. Each user has a score which can be calculated using the data from the questions and answers tables. Therefore if I had a score field in the users table, it would be redundant. However, if I don't use a score field, then calculating the score every time would significantly slow down the website.

My current solution is to put it in a score field, and then have a cron running every few hours which recalculates everybody's score, and updates the field.

Is there a better way to handle this?

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

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

发布评论

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

评论(1

柏林苍穹下 2024-09-08 20:00:31

在我看来,消除冗余对于创建高效(且清晰!​​)的代码来说是次要的。

与其使用 cron 来更新分数,为什么不创建触发器 在适当的位置插入记录时更新用户的分数?

如果是在更新 answers 表时更新分数的问题,那么您会执行类似以下操作:

create trigger 'scores_increment'
    after insert on 'answers'
    for each row begin
        update 'users' set user_score = user_score + 1 where user_id = NEW.user_id;
    end;

create trigger 'scores_decrement'
    after delete on 'answers'
    for each row begin
        update 'users' set user_score = user_score - 1 where user_id = NEW.user_id;
    end;

尽管 DBMS 偶尔会“打嗝”并忘记运行触发器或其他操作。我建议将设置分数的原始 cron 脚本每周运行一次。

In my opinion, eliminating redundancy is secondary to creating efficient (and legible!) code.

Instead of using cron to update the score, why not create a trigger to update the user's score when a record is inserted in the appropriate place?

If it's a matter of updating scores when when the answers table is updated, then you would do something like this:

create trigger 'scores_increment'
    after insert on 'answers'
    for each row begin
        update 'users' set user_score = user_score + 1 where user_id = NEW.user_id;
    end;

create trigger 'scores_decrement'
    after delete on 'answers'
    for each row begin
        update 'users' set user_score = user_score - 1 where user_id = NEW.user_id;
    end;

Although, occasionally, DBMSes 'hiccup' and forget to run a trigger, or something. I'd suggest putting your original cron script that sets the scores to running once a week.

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