mysql分组取每组最⼤_MySQL获取分组后每组最⼤的数据需求
有两个表:游戏表、视频表,⼀个游戏对应多个视频,取出排在最前⾯的 5 个游戏的视频(每个游戏只选取他所有视频的第⼀个),视频排序按照视频表的顺序(Video.level)
最终解决⽅法:
SELECT * FROM `tbl_video` AS `Video` LEFT OUTER JOIN `tbl_game` AS `Game`
ON `Video`.`gameId` = `Game`.`id`
WHERE `Video`.`level` in (SELECT MAX(`level`) FROM `tbl_video` GROUP BY `gameId`) AND `Video`.`isShow` = 1
ORDER BY `Video`.`level` DESC LIMIT 0, 5
⽹上盛传的⼦查询解决⽅案貌似是错误的免费mysql视频教程
数据库 test:
id
name
gameId
level
1
a
1
1
2
b
2
2
3
c
1
3
4
d
1
4
5
e
2
5
运⾏⼦查询语句
select * from (select * from `test` order by `level` desc) `temp` group by `gameId` order by `level` desc
得到
id
name
gameId
level
2
b
2
2
1
a
1
1
group by 只是每组取⼀个代表值,⽬测没有什么规律(待验证)
解决⽅法
select * from `test` where `level` in (
SELECT substring_index(group_concat(`level` order by `level` desc SEPARATOR ','),",",1) from `test` GROUP BY `gameId` ) order by `level` desc;
这个⽐较灵活,可以在 group by 后,再按结果集⾥的再进⾏⾃⼰想要的字段排序等。
这个可以⾃由实现获取分组后,第 N ⼤的数据。⽐如,分组后,第 N ⼤的数据:
select * from `test` where `level` in (
SELECT substring_index(substring_index(group_concat(`level` order by `level` desc SEPARATOR ','),",",N), ",",-1)
from `test` GROUP BY `gameId`
) order by `level` desc;
将 N 改为你⾃⼰想要的数字即可(但是超过数量以后会求最末尾的那⼀个),⽽最上⾯的⽅法只能求最⼤最⼩。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。