[英]how to get a sql rank query working to find the rank of a specific id
我尝试进行排名查询,但无法使其正常工作。 排名由最高的market_cap 后跟最高的id 计算,如果market_cap 具有相同的值,则条件active 必须为1。我只想要最后一个特定id 的排名。
桌子:
ID | 市值 | 积极的 | 预期排名 |
---|---|---|---|
1 | 67000 | 1 | 4 |
2 | 197000 | 1 | 1 |
3 | 67000 | 1 | 3 |
4 | 127000 | 1 | 2 |
5 | 17000 | 1 | 5 |
6 | 37000 | 1 | 5 |
7 | 2237000 | 0 | / |
这是 PHP(Laravel) 代码,它可以做到这一点并且正在工作,但我想将它用作普通的 SQL 以提高速度,因为我的表有 20k 行。
$token_list = DB::table('tokens')->where('active', 1)->orderBy('market_cap', 'desc')->orderBy('id', 'desc')->get(array('id'));
foreach($token_list as $key => $token){
if($token->id == $data['token']->id){
$token_rank = $key+1;
}
}
尚未工作的当前查询(它停止对所有 market_cap 为 0 的结果工作,即数千个,它们都获得相同的排名,即最后一个排名数字):
$rank_query = DB::select("SELECT FIND_IN_SET(market_cap, ( SELECT GROUP_CONCAT(market_cap ORDER BY market_cap DESC, id DESC) FROM tokens WHERE active = 1)) AS rank FROM tokens WHERE id = {$data['token']->id}");
$token_rank = $rank_query[0]->rank;
在 SQL 查询中,您可以使用row_number()
:
select t.*
from (select t.*,
(case when active
then row_number() over (partition by active order by market_cap desc, id desc)
end) as ranking
from t
) t
where . . .
您可以将过滤条件放在外部查询中。
你也可以使用 Laravel 的查询构建器来做类似的事情。 无需使用原始 sql。
$marketCapQuery = DB::table('tokens')->selectRaw('GROUP_CONCAT(market_cap ORDER BY market_cap DESC, id DESC)'->where('active', 1)->toSql();
$rank_query = DB::table('tokens')->selectRaw("FIND_IN_SET(market_cap, ( '.$marketCapQuery.') AS rank'->where('id', $data['token']->id);
$token_rank = $rank_query[0]->rank;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.