开发者

PHP-MYSQL raiting comments

i have a question probably you will consider it stupid but anyway

while making in php comments , i thought that would be cool if people can rate a comment with +1/-1 so i did one Table in the DB for the comments (id, user_id, comment, time) and another on开发者_JAVA技巧e for the rating comments (id_rate, id_comment, id_user, time) i use the id_user so he can not rate two times the same comment

well the problem is the following: if a blog post has like 100 comments and each has like 200 votes (+1 or -1) wouldn't be the page too slow to load, lots and lots of queries just to load a few comments?

is another way around to do this following the normal forms of DBs?

Thanks for your time, i really appreciate it.


To get the comments and their ratings can be done in a single SQL-query. It will be slow when you have A LOT of comments and ratings, but not for the numbers you mention.

If you want to make it faster, you can create an attribute on the comments named "rating" or something like that, and update it every hour (or how often you think will suffice) or so. It will not be exact, but it will approximate the commentrating. But we are talking millions of comments and ratings here before it is nescesarry.

This would normally be done with a materialized view, but that is unfortunately not implemented in MySQL... You can use the method described above though by writing a php-script and running it through a cronjob.

Use a query like this (untested):

SELECT * 
FROM comments, ratings 
WHERE comments.id = ratings.id_comment;

assuming you add a value to your votes (+1 or -1) you can group them and calculate the total commentrating in one query like this (untested):

SELECT comments.id, comments.user_id, comments.comment, 
       comments_time, SUM(ratings.value) AS rating
FROM comments, ratings
WHERE comments.id = ratings.id_comment
GROUP BY comments.id;

You will now have all the commentfields and the calculated commentrating as the field rating. If you want to speedtest it you can try to insert a million dummy comments and a million ratings and see how long the query takes.

To speed it up even more you can add an index on comments.id_comment like this:

CREATE INDEX speedthisthingup ON comments(id_comment);

That should help the execution time a great deal :)

Good luck!


You could cache the current comment vote in the comments table with another field called commentvote. Otherwise, checking the rating comments table to verify the user hasn't already voted should be relatively fast with appropriate indexes.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜