优化Mysql以避免冗余但仍能快速访问可计算数据
为了解决这个问题,举一个例子:我有一个包含用户、问题和答案的数据库。每个用户都有一个分数,可以使用问题和答案表中的数据来计算。因此,如果我在用户表中有一个分数字段,那么它将是多余的。但是,如果我不使用分数字段,那么每次计算分数都会显着减慢网站速度。
我当前的解决方案是将其放入分数字段中,然后每隔几个小时运行一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我看来,消除冗余对于创建高效(且清晰!)的代码来说是次要的。
与其使用 cron 来更新分数,为什么不创建触发器 在适当的位置插入记录时更新用户的分数?
如果是在更新
answers
表时更新分数的问题,那么您会执行类似以下操作:尽管 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: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.