mysql中group by 和 order by一起使用

记录一下自己在项目中遇到的一个问题并且是如何解决的

使用数据模拟一下
`
班级表
在这里插入图片描述
学生表
在这里插入图片描述
花费表
在这里插入图片描述

对应的建表sql:
create table stu(
id int not null auto_increment,
name varchar(256) not null default ‘’ comment ‘学生姓名’,
cla_id int not null default 0 comment ‘班级’,
primary key (id)
)

create table cla(
id int not null auto_increment,
title varchar(256) not null default ‘’ comment ‘班级名称’,
primary key (id)
)

create table spend(
id int not null auto_increment,
stu_id int not null default 0 comment ‘学生id’,
amount int not null default 0 comment ‘花费’,
primary key (id)
)
`
如上三表我们要查询要按最高的一次花费进行排名,并且罗列出学生姓名班级信息,这个时候我们肯定会想到使用group by 和 order by 组合使用,如下查询语句:


select s.stu_id,s.amount,x.name,c.title from (select stu_id,amount from spend group by stu_id order by amount desc) s left join stu x on x.id = s.stu_id left join cla c on c.id = x.cla_id;

在这里插入图片描述

这样查询其实查询不到最高的一次消费,还存在一个问题,在项目中使用如上类型的sql会报错,因为group by 和order by 一起使用的话需要满足order by在group by 后面,且order by 排序字段需要在group by 中,这点我觉得很坑。但是在自己电脑环境上使用不会报错,有点尴尬。但是总体来说还是不能达到预期的效果。

select s.stu_id,s.amount,x.name,c.title from (select stu_id, max(amount) as amount from spend group by stu_id order by amount desc) s left join stu x on x.id = s.stu_id left join cla c on c.id = x.cla_id;

在这里插入图片描述
如上使用了一个max()取值最大的函数之后就可以达到我们预期的效果,sql语句可能还有更优化的解决方案。
性能的话自测会有损耗,不过我使用在管理端,这种并发情况不高的情况下是可以接受的。
这个得前提是框架的model不能满足你的开发需求,但是你又不想改框架的model,可以尝试一下这个方法。

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值