Rating System in PHP and MySQL

前端 未结 3 1599
花落未央
花落未央 2021-01-21 15:00

If we look at the stackoverflow website we have votes. But the question is what is the bestway to store who has voted and who has not. Lets also simplify this even more and say

相关标签:
3条回答
  • 2021-01-21 15:16

    I believe your design won't be able to scale for large numbers of voters. The typical thing to do is to create to tables

    Table 1: question - Id(INT) | userId(INT) | title(TEXT)
    Table 2: question - ID(INT) | vote(INT) | ratedBy(TEXT)

    Then you can count the votes with a query like this:

    SELECT t1.question_Id, t1.userId, t1.title, t2.sum(vote)
    FROM table1 t1
    LEFT JOIN table2 t2 ON t1.question_id = t2.question_id
    
    0 讨论(0)
  • 2021-01-21 15:23

    A new table:

    Article ID | User ID | Rating

    Where Article ID and User ID make up the composite key, and rating would be 1, indicating upvote, -1 for a downvote and 0 for a removed vote (or just remove the row).

    0 讨论(0)
  • 2021-01-21 15:27

    I think to make another table "vote" is better. The relationship between users and votes is n to n, therefore a new table should be created. It should be something like this:

    question id (int) | user id (int) | permanent (bool) | timestamp (datetime)
    

    Permanent field can be used to make votes stay after a given time, as SO does.
    Other fields may be added according to desired features. As each row will take at least 16B, you can have up to 250M rows in the table before the table uses 4GB (fat32 limit if there is one archive per table, which is the case for MyISAM and InnoDB).
    Also, as Matthew Scharley points out in a comment, don't load all votes at once into memory (as fetching all the table in a resultset). You can always use LIMIT clause to narrow your query results.

    0 讨论(0)
提交回复
热议问题