当前位置:网站首页>Mysql 5.7 取分组第一条
Mysql 5.7 取分组第一条
2022-07-26 23:23:00 【水晶心泉】
以下表为例,需要取每个班级、被选的次数最多的学科,比如1班的有三个选数学的,一个选语文的,那么期望返回的是数学,其他同理。
| id | name | class | course |
|---|---|---|---|
| 1 | 张三 | 1 | 数学 |
| 2 | 李四 | 1 | 数学 |
| 3 | 王五 | 1 | 数学 |
| 4 | 赵六 | 1 | 语文 |
| 5 | 黑七 | 2 | 语文 |
| 6 | 猪八 | 2 | 语文 |
| 7 | 琴九 | 2 | 数学 |
| 8 | 王十 | 3 | 数学 |
| 9 | 毛十一 | 3 | 数学 |
| 10 | 萧十二 | 3 | 数学 |
| 11 | 阿十三 | 3 | 语文 |
第一种方法: limit + group by
例
SELECT t.*
FROM
(
SELECT ta.class,ta.course,count(*) as counts
FROM courses as ta
group by ta.class,ta.course
order by counts desc // 在这里排序
LIMIT 1000 //这里是必须的,而且好像最大值是1万
) t
GROUP BY t.class //外层使用分组
返回结果如下
| class | course | counts |
|---|---|---|
| 1 | 数学 | 3 |
| 2 | 语文 | 2 |
| 3 | 数学 | 3 |
在站内找了几篇博文,基本都是这个套路,也许这种方法性能会好一些,而且好像可以直接取到最大值那一整行的数据,可以说非常方便了。
比如这篇博文还对优化进行了分析:https://blog.csdn.net/u013066244/article/details/116461584
但是:由于公司服务器启用了ONLY_FULL_GROUP_BY,所以没法使用。
第二种方法:group_concat+substring_index
select tb.class,SUBSTRING_INDEX(GROUP_CONCAT(tb.course order by counts desc),',',1) as course
from
(
SELECT ta.class,ta.course,count(*) as counts
FROM courses as ta
group by ta.class,ta.course
) as tb
group by tb.class;
返回结果如下
| class | course |
|---|---|
| 1 | 数学 |
| 2 | 语文 |
| 3 | 数学 |
关于这个方法,已经有博主写过了,个人觉得很详细了,连接在此:https://blog.csdn.net/MyfishCake/article/details/120175776
边栏推荐
- PPOCRLabel格式的数据集操作总结。
- HCIP-第四天-OSPF路由协议
- Rip routing information protocol topology experiment
- [C language programming] branch structure
- LeetCode->二分法(三)
- 膜拜,阿里内部都在强推的321页互联网创业核心技术pdf,真的跪了
- 静态路由实验配置
- How many holes have you stepped on in BigDecimal?
- Solve prime numbers between 100 and 200
- After working in Tencent testing post for 5 years, I was ruthlessly dismissed in July, trying to wake up my brother who was still paddling
猜你喜欢

HCIP-第一天

Plato Farm有望通过Elephant Swap,进一步向外拓展生态

Record the star user of handsomeblog

RIP路由信息协议-拓扑实验

Graduated and entered HW, from test engineer to project manager. Now I earn millions in goose factory every year. My suggestions to you

Hcip first day static routing comprehensive experiment

Hcip first day

白盒测试案例设计(我爷爷都能看懂)

Hcip the next day
![[C language] factorial implementation](/img/a1/9e603321d364c7f457116bd9e462aa.png)
[C language] factorial implementation
随机推荐
【自此文之后,学习链表一片坦途】
Go language slow start - package
BigDecimal 的 4 个坑,你踩过几个?
小程序utils
HCIP-第一天
软件测试基础理论知识—概念篇
Interesting C language
Today, let's talk about escape characters [cute new version]
【用C语言绘制直角坐标系】
[C language programming] branch structure
Rip routing information protocol topology experiment
js utils 零碎
【Code】剑指offer 04二维数组中的查找
Hcip OSPF interface network interface type experiment
【洋哥带你玩转线性表(一)——顺序表】
使用注解方式实现 Redis 分布式锁
Record the nth SQL exception
聊聊自动化测试的度量指标
Solve every bit of an integer
Risc-v tool chain compilation notes