开发者

Optimizing Mysql to avoid redundancy but still have fast access to calculable data

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 qu开发者_运维技巧estions 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜