PHP查询用户排名名次、Mysql查询用户排名名次的方法,最近做了用户排行榜,那么就整理了查询用户排行的一些代码,主要分为两部分:PHP、Mysql两者独立查询用户排名信息,当然查询的是所有用户的排名以及当前用户的排名信息。
假设我们有一张用户表:
1、PHP查询方法:直接使用PHP的方式并不是特别推荐的方式,如果数据多的话,筛选可能就比较慢
//获取当前用户信息
$where = [];
$where[] = ['status', '=', 1];
$userinfo = \Db::name('user')->field('openid,nickname,score,last_score_time')->where($where)->find();
//获取积分列表,限制1000条
$where = [];
$where[] = ['status', '=', 1];
$where[] = ['score', 'gt', 0];
$ranking = \Db::name('user')->field('openid,nickname,score,last_score_time')->where($where)->order('score desc,last_score_time asc')->limit(1000)->select();
//数据
$data = [];
//当前用户默认排名
$data['user']['openid'] = $userinfo['openid'];
$data['user']['nickname'] = $userinfo['nickname'];
$data['user']['score'] = $userinfo['score'];
$data['user']['last_score_time'] = $userinfo['last_score_time'];
$data['user']['ranking'] = "1000+"; //超过1000的就显示1000+
if(!empty($ranking)){
foreach ($ranking as $key => $value) {
//排名
$ranking_name = $key + 1;
$ranking[$key]['ranking'] = $ranking_name;
//当前用户排名
if($value['openid'] == $params['openid']){
$data['user']['openid'] = $value['openid'];
$data['user']['nickname'] = $value['nickname'];
$data['user']['score'] = $value['score'];
$data['user']['last_score_time'] = $value['last_score_time'];
//排名
$data['user']['ranking'] = $ranking_name;
}
}
}
//排名列表,取100个
$data['list'] = array_slice($ranking, 0, 100);
2、Mysql查询方法:推荐方式,直接使用mysql查询是比较方便的,也可以结合PHP原生mysql语句查询
1)、查询所有排名信息
查询语句:
SELECT
p.openid,
p.nickname,
p.score,
@rownum := @rownum + 1 AS rownum
FROM
(SELECT
@rownum := 0) r,
(SELECT
*
FROM
`aikehou_wechat_bljl_user`
WHEREscore > 0
ORDER BY score DESC,
last_score_time ASCLIMIT1000) AS p
查询结果:
2)、查询当前用户排名信息
查询语句:
SELECT
b.openid,
b.nickname,
b.score,
b.rownum
FROM
(SELECT
t.*,
@rownum := @rownum + 1 AS rownum
FROM
(SELECT
@rownum := 0) r,
(SELECT
*
FROM
`aikehou_wechat_bljl_user`
WHERE score > 0
ORDER BY score DESC,
last_score_time ASC) ASt) AS b
WHEREb.openid = "oHL30wVEuI58L22gp8dkQ23232mSSW4dU4g";
查询结果:
解释:
1、SELECT @rownum := 0:表示对rownum赋初始值0
2、@rownum := @rownum + 1:表示对rownum加1,语句中会从1开始,每一行往下都自动加1
3、所有用户排名是先对用户表进行积分排序,然后对名次进行累加;当前用户排名,就是在筛选出所有用户排名的基础上再进行当前用户信息进行筛选,说白了就是Mysql的组合查询