Best practice for comment voting database structure

被刻印的时光 ゝ 提交于 2019-12-04 12:28:38

问题


I'm working on a PHP app that has several objects that can be commented on. Each comment can be voted on, with users being able to give it +1 or -1 (like Digg or Reddit). Right now I'm planning on having a 'votes' table that has carries user_id and their vote info, which seems to work fine.

The thing is, each object has hundreds of comments that are stored in a separate comments table. After I load the comments, I'm having to tally the votes and then individually check each vote against the user to make sure they can only vote once. This works but just seems really database intensive - a lot of queries for just the comments.

Is there a simpler method of doing this that is less DB intensive? Is my current database structure the best way to go?

To be clearer about current database structure:

Comments table:

  • user_id
  • object_id
  • total_votes

Votes table:

  • comment_id
  • user_id
  • vote

End Goal:

  • Allow user to vote only once on each comment with least # of MySQL queries (each object has multiple comments)

回答1:


To make sure that each voter votes only once, design your Votes table with these fields—CommentID, UserID, VoteValue. Make CommentID and UserID the primary key, which will make sure that one user gets only one vote. Then, to query the votes for a comment, do something like this:

SELECT SUM(VoteValue)
FROM Votes
WHERE CommentID = ?

Does that help?




回答2:


Why don't you save the totaled votes for every comment? Increment/decrement this when a new vote has happened.

Then you have to check if the user has voted specifically for this comment to allow only one vote per comment per user.




回答3:


You can put a sql join condition which returns all the votes on comments made by the current user for this object, if you get no rows, the user hasn't voted. That is just slightly different from you checking each comment one by one in the program.

as far as the database structure is concerned, keeping these things separate seems perfectly logical. vote { user_id, object_id, object_type, vote_info...)

You may be already doing this, sorry but I couldn't interpret from you post if that was the case.



来源:https://stackoverflow.com/questions/809916/best-practice-for-comment-voting-database-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!