查询问题排名系统MYSQL
Query issue ranking system MYSQL
我有一个排名系统,我会在每个比赛日保存用户排名和积分。
现在我的问题是我想获取用户自昨天以来攀升的排名位置数。所以在这个例子中 user_id = 1 自昨天以来已经下降了 3 个位置。我当前的查询给了我想要的东西,但有一些我想删除的额外计算。所以我的问题是如何计算每个用户(今天和昨天之间)的排名差异?
SQL FIDDLE
SELECT current.user_id,(last.rank -current.rank)
FROM ranking as current
LEFT JOIN ranking as last ON
last.user_id = current.user_id
WHERE current.rank_date = (SELECT max(rank_date) FROM ranking)
and
last.rank_date = (SELECT max(rank_date) FROM ranking
where rank_date < (SELECT max(rank_date) FROM ranking)
)
So my question is how do I calculate the difference in rank for every
user (between today and yesterday)?
关于你的 sqlfiddle 演示,我想你想要这个输出:
user_id diff
1 3
1 -3
2 -1
2 -1
所以试试这个:
SELECT current.user_id,(last.rank - current.rank) as diff
FROM ranking as current
LEFT JOIN ranking as last
ON last.rank_date = current.rank_date+1
and last.user_id = current.user_id
where last.rank_date is not null
order by current.user_id
我认为最简单的方法是:
SELECT today.user_id, (yest.rank - today.rank) as diff
FROM ranking today JOIN
ranking yest
on today.user_id = yest.user_id
WHERE today.rank_date = CURRENT_DATE AND
yest.rank_date = date_sub(CURRENT_DATE, interval 1 day);
我有一个排名系统,我会在每个比赛日保存用户排名和积分。
现在我的问题是我想获取用户自昨天以来攀升的排名位置数。所以在这个例子中 user_id = 1 自昨天以来已经下降了 3 个位置。我当前的查询给了我想要的东西,但有一些我想删除的额外计算。所以我的问题是如何计算每个用户(今天和昨天之间)的排名差异? SQL FIDDLE
SELECT current.user_id,(last.rank -current.rank)
FROM ranking as current
LEFT JOIN ranking as last ON
last.user_id = current.user_id
WHERE current.rank_date = (SELECT max(rank_date) FROM ranking)
and
last.rank_date = (SELECT max(rank_date) FROM ranking
where rank_date < (SELECT max(rank_date) FROM ranking)
)
So my question is how do I calculate the difference in rank for every user (between today and yesterday)?
关于你的 sqlfiddle 演示,我想你想要这个输出:
user_id diff
1 3
1 -3
2 -1
2 -1
所以试试这个:
SELECT current.user_id,(last.rank - current.rank) as diff
FROM ranking as current
LEFT JOIN ranking as last
ON last.rank_date = current.rank_date+1
and last.user_id = current.user_id
where last.rank_date is not null
order by current.user_id
我认为最简单的方法是:
SELECT today.user_id, (yest.rank - today.rank) as diff
FROM ranking today JOIN
ranking yest
on today.user_id = yest.user_id
WHERE today.rank_date = CURRENT_DATE AND
yest.rank_date = date_sub(CURRENT_DATE, interval 1 day);