php - 遇到一个查询问题,不知道用 mysql 怎么查,详细信息写在里面了,求大神指点
ringa_lee
ringa_lee 2017-04-11 10:21:11
[PHP讨论组]

假设我有一个存放学生分数的表,有两个字段,student_idscore,假设我每天存一次,但是存的分数不一样。现在我要查所有记录,结果如下:

[
    {'student_id':5, 'score': 7},
    {'student_id':5, 'score': 3},
    {'student_id':6, 'score': 9},
    {'student_id':6, 'score': -2},
    {'student_id':7, 'score': 8},
    {'student_id':7, 'score': 6},
]

现在我有一个需求,查询所有信息,用 student_id 分组,并将相同的 student_id 的 score 相加,然后 score 倒序,结果如下:

[
    {'student_id':7, 'score': 14},
    {'student_id':5, 'score': 10},
    {'student_id':6, 'score': 7},
]

求大神解答!

ringa_lee
ringa_lee

ringa_lee

全部回复(2)
大家讲道理

select student_id,sum(score) from 表名 group by student_id order by score desc

PHPz

@ShanaMaid @杨成功
按照需求来看,最终排序的凭据是总分。那么楼上order by score desc会有错误

select student_id,sum(score) as total from student group by student_id order by total desc

可以对比一下

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号