MySQL:基于外部行的范围 table
MySQL: Range based on rows in external table
我正在使用 MySQL 来解决这个问题。我需要根据用户在某个问题上花费的总时间来给用户打分。我计算了用户花费的时间。假设它在 user_time table.
user_id question_id time_spent
1 1 7
1 2 50
2 1 11
我的积分是基于范围的:
[0-10) seconds: 100 points,
[10-20) seconds: 300 points,
[20-30) seconds: 500 points,
[30, inf): 1000 points
准确的 10 秒将给我 300 分。不过,鉴于我是根据系统时钟差异计算的,确切数字的变化会很低。
此信息目前在外部评分tablepoints_table
time_spent points
0 100
10 300
20 500
30 1000
我需要一个查询来找出秒属于哪个范围并给我那个结果。
user_id question_id points
1 1 100
1 2 1000
2 1 300
我尝试考虑不同类型的联接,但想不出一种可以满足这一特定要求的联接。
我认为最简单的方法是相关子查询。像这样:
select ut.*,
(select pt.points
from points_table pt
where pt.time_spent <= ut.time_spent
order by pt.time_spent desc
limit 1
) as points
from user_time ut
试试这个:
SELECT ut.user_id, ut.time_spent, A.points
FROM user_time ut
INNER JOIN (SELECT p1.time_spent AS time_spent1,
p2.time_spent AS time_spent2,
p1.points
FROM points_table p1
INNER JOIN points_table p2 ON p1.time_spent < p2.time_spent
GROUP BY p1.time_spent
) AS A ON ut.time_spent BETWEEN A.time_spent1 AND A.time_spent2
换个角度看,你可以在没有分数的情况下获得相同的结果table:
SELECT *,
CASE
WHEN time_spent >= 30 THEN 1000
WHEN time_spent >= 20 THEN 500
WHEN time_spent >= 10 THEN 300
ELSE 100
END 'Points'
FROM user_time;
我正在使用 MySQL 来解决这个问题。我需要根据用户在某个问题上花费的总时间来给用户打分。我计算了用户花费的时间。假设它在 user_time table.
user_id question_id time_spent
1 1 7
1 2 50
2 1 11
我的积分是基于范围的:
[0-10) seconds: 100 points,
[10-20) seconds: 300 points,
[20-30) seconds: 500 points,
[30, inf): 1000 points
准确的 10 秒将给我 300 分。不过,鉴于我是根据系统时钟差异计算的,确切数字的变化会很低。
此信息目前在外部评分tablepoints_table
time_spent points
0 100
10 300
20 500
30 1000
我需要一个查询来找出秒属于哪个范围并给我那个结果。
user_id question_id points
1 1 100
1 2 1000
2 1 300
我尝试考虑不同类型的联接,但想不出一种可以满足这一特定要求的联接。
我认为最简单的方法是相关子查询。像这样:
select ut.*,
(select pt.points
from points_table pt
where pt.time_spent <= ut.time_spent
order by pt.time_spent desc
limit 1
) as points
from user_time ut
试试这个:
SELECT ut.user_id, ut.time_spent, A.points
FROM user_time ut
INNER JOIN (SELECT p1.time_spent AS time_spent1,
p2.time_spent AS time_spent2,
p1.points
FROM points_table p1
INNER JOIN points_table p2 ON p1.time_spent < p2.time_spent
GROUP BY p1.time_spent
) AS A ON ut.time_spent BETWEEN A.time_spent1 AND A.time_spent2
换个角度看,你可以在没有分数的情况下获得相同的结果table:
SELECT *,
CASE
WHEN time_spent >= 30 THEN 1000
WHEN time_spent >= 20 THEN 500
WHEN time_spent >= 10 THEN 300
ELSE 100
END 'Points'
FROM user_time;