您的当前位置:首页 > 资讯 > postgresql
sql查询出来是语句进行自增排序
2018-08-29 14:49:26 来源:admin 点击:881
//先查出来数据
$data = DB::select("select A,B, row_number() over(order by B desc) as D,
A, row_number() over(order by C desc) as C ,
F, row_number() over(order by F desc) as F ,
s , row_number() over(order by s desc) as s
from people where testid = ".$testid);
//循环插入rank
foreach ($data as $key=>$v){
$updRank = DB::table('people')
->where('name',$v->name)
->where('testid',$testid)
->update([
'A' => $v->A,
'B' => $v->B,
'C' => $v->C,
'D' => $v->D
]);
}
return $updRank;
核心是row_number() over (order by 字段 desc) as V 查出来的就是按照字段进行递减排序,注意思想,代码有可能不对。上面的方法有一个弊端,就是排名出来后相同成绩的排名不相同,所以得用下面的方法更新一下排名
/*
* 更新排名
* @zfx
* */
public function updRankcheck(Request $request){
set_time_limit (100);
//先查出来数据
$eventcountrank = DB::table('people')
->where('testid',$testid)
->select('A成绩','a排名','b成绩','b排名','c成绩','c排名')
->get();
foreach ($eventcountrank as $v){
foreach ($eventcountrank as $vv){
// 如果成绩相同,取最小排名,更新其他两个的排名成最小排名
if($v->A成绩== $vv->A成绩){
$A排名_min = DB::table('people')->where('A成绩',$v->A成绩)->min('A排名');
$updRank = DB::table('people')
->where('A成绩',$v->A成绩)
->update([
'A排名' => $A排名_min
]);
}
if($v->b成绩== $vv->b成绩){
$rivercount_min = DB::table('people')->where('b成绩',$v->b成绩)->min('b排名');
$updRank = DB::table('people')
->where('b成绩',$v->b成绩)
->update([
'b排名' => $rivercount_min,
]);
}
}
}
if($updRank){
DB::commit();
return ['status' => 200, 'msg' => '更新成功'];
}else{
DB::rollBack();
return ['status' => 400, 'msg' => '更新失败,请稍后再试'];
}
}
$rivercount = DB::table('people')
->select('id','A成绩','A排名')
->orderBy('A成绩','desc')
->get();
$count1 = -999;
$kkk1 = 0;
foreach ($rivercount as $v){
//更新A成绩
if ($v->A成绩 != $count1){
$kkk1 += 1;
//把他赋值给下一个,指针逻辑,不过php没指针
$count1 = $v->A成绩;
}
$updRank1 = DB::table('people')
->where('id',$v->id)
->update([
'A排名' => $kkk1
]);
}
//更新B成绩
$riverkm = DB::table('people')
->select('id','B成绩','riverkmrank')
->orderBy('B成绩','desc')
->get();
$count2 = -999;
$kkk2 = 0;
foreach ($riverkm as $v){
//更新rivercount
if ($v->B成绩!= $count2){
$kkk2 += 1;
$count2 = $v->B成绩;
}
$updRank2 = DB::table('people')
->where('id',$v->id)
->update([
'B排名' => $kkk2
]);
}
上面的方法亲测可以,但不支持大并发,支持大并发的方法如下:(批量更新)
UPDATE 表 as a set rivercountrank = b.rivercountrank from (select rivercount, row_number() over(order by rivercount desc) as rivercountrank from 表 where testid = ".$testid." GROUP BY rivercount) as b where a.rivercount = b.rivercount