简体   繁体   English

根据总分和时间获取用户排名位置

[英]Get user rank position based on total score and time

I want to get the user rank position based on the total score and average time. 我想根据总分和平均时间来获得用户排名位置。 However, the query I am using gives the wrong position number. 但是,我正在使用的查询给出了错误的职位编号。

$myId = TotalScore::where('user_id', $user_id)->first();
$position = TotalScore::where('ts', '>=', $myId->ts)
    ->where('avg_times_taken', '>=', $myId->avg_times_taken)->count();

Table structure 表结构

在此处输入图片说明

Let's say I want to know my rank position. 假设我想知道我的排名。 The query needs to compare my total score (ts) and the average time taken ( avg_times_taken ) and display my position. 查询需要比较我的总得分(ts)和平均花费时间( avg_times_taken ),并显示我的位置。 If two users get the same score, the one with the lower average time ranked better. 如果两个用户获得相同的分数,则平均时间较低的用户排名会更好。

From the above comments, it is clear that total score and the average time taken are inversely related. 从以上评论可以明显看出,总分与平均花费时间成反比。 Ie the ratio between the total_score and average_time_taken, should give us some value that we'll now use to position or order our records. 即total_score和average_time_taken之间的比率应该给我们一些值,我们现在将使用它来定位或排序记录。 Hence, first, I would introduce another column in the table and calculate the ratio. 因此,首先,我将在表中引入另一列并计算比率。 Assuming we call the column ratio_average 假设我们将列ratio_average

to get values for our column simply take total_score / average_time_taken 要获取我们列的值,只需采用total_score / average_time_taken

so now when fetching our results from the table we'd only have to do the following: 因此,现在从表中获取结果时,我们只需执行以下操作:

TotalScore::orderBy('ratio_average', 'desc')->get();

Above will now give you the results in the correct order of positions from the first position 上面的内容将按照从第一个位置开始的正确位置顺序为您提供结果

This is what a MySQL query would look like : 这就是MySQL查询的样子:

SELECT 
    (
      SELECT COUNT(*)
      FROM TableScore X
      WHERE X.ts > T.ts OR (X.ts = T.ts AND X.avg_times_taken < T.avg_times_taken)
    ) + 1 AS position   
FROM TableScore T      
WHERE T.user_id = '7';

WORKING DB-FIDDLE EXAMPLE HERE 在这里使用DB字段示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM