Mysql和MongoDB查询排名

xiaohai 2019-11-17 16:16:02 3095人围观 标签: Mysql  MongoDB 
简介如何通过查询语句来查询某个数据的排名,本文主要介绍MySql和MongoDB两种数据库的查询方式来进行排名。
一、Mysql查询排名
SELECT * FROM (SELECT student_id,(@rowNum:=@rowNum+1) AS rowNo FROM students,(SELECT(@rowNum:=0)) b ORDERBY age DESC) c WHERE student_id=216;
二、MongoDB查询排名
db.getCollection("students").aggregate([ {$sort:{score:-1}}, //按照分数排序 {$group:{_id:null,all:{$push:"$student_id"}}}, // 将所有排序结果push到all数组中,方便下面使用$indexOfArray {$project:{_id:0,total:{$size:"$all"},index:{ $indexOfArray:[ "$all",student_id] }}} // 这里的student_id为要查找名次的openid ])

注意:

  • {group:{_id:null,all:{push:"student_id"}}}这条语句中的student_id一定不能省略掉$符号。
  • {project:{_id:0,total:{size:"$all"},index:{ indexOfArray:["indexOfArray:[ "all",student_id] }}} 这里的student_id是对应的学生ID