Вопрос

I'm working on how to implement a leaderboard. What I'd like to do is be able to sort the table by several different filters(score,number of submissions, average). The table might look like this.

+--------+-----------------------+------+-----+---------+-------+
| Field  | Type                  | Null | Key | Default | Extra |
+--------+-----------------------+------+-----+---------+-------+
| userID | mediumint(8) unsigned | NO   | PRI | 0       |       |
| score  | int                   | YES  | MUL | NULL    |       |
| numSub | int                   | YES  | MUL | NULL    |       | 
+--------+-----------------------+------+-----+---------+-------+

And a sample set of data like so:

+--------+----------+--------+
| userID | score    | numSub |
+--------+----------+--------+
| 505610 | 1245     | 2      |    
| 544222 | 1458     | 2      |
| 547278 | 245      | 1      |
| 659241 | 12487    | 8      |
| 681087 | 5487     | 3      |
+--------+----------+--------+

My queries will be coming from PHP.

// get the top 100 scores
$q = "select userID, score from table order by score desc limit 0, 100";

this will return a set of userID/score sorted highest score first I also have a query to sort by numSub (number of submissions)

What I would like is to sort the table by the avg score that being score/numSub; The table could be large so efficiency is important to me.

Thanks in advance!

Это было полезно?

Решение

If efficiency is important, then add a column avgscore and assign it the value of score/numsub. Then, create an index on the column.

You can use an insert/update trigger to do the average calculation automatically when a row is added or modified.

Once your tables gets large, the sort is going to take a noticeable amount of time.

Другие советы

As far as I can see, there's no reason to make it more complicated than this;

SELECT userID, score/numsub AS average_score
FROM Table1 
ORDER BY score/numsub DESC;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top