mysql的分组排序limit问题

作者:matrix 被围观: 7,541 次 发布时间:2018-05-03 分类:零零星星 | 一条评论 »

这是一个创建于 2184 天前的主题,其中的信息可能已经有所发展或是发生改变。

业务要求按照type,city分组,然后各取前面的100条数据输出,网上找到了类似的需求直接sql语句就可以解决。

测试表结构


CREATE TABLE `esc_catch` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `city` varchar(20) NOT NULL DEFAULT '' COMMENT '城市', `price` decimal(10,2) unsigned NOT NULL DEFAULT '0.00' COMMENT '报价', `type` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '1,2', `add_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '添加时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB   DEFAULT CHARSET=utf8mb4

解决办法


set @row=0;set @city=''; set @type=''; select a.city,a.price,a.type ,from_unixtime(a.add_time,'%Y-%m-%d %H:%i:%s') as add_time from esc_catch as a inner join ( SELECT id,add_time, case when (@city = city and @type= type) then @row:=@row+1 else @row:=1 end as rownum, @city:=city as city , @type:=type as type FROM esc_catch order by type,city,add_time desc ) as b on b.id = a.id where b.rownum>=100 order by b.type,b.city ;

说明:

头部事先声明变量
row 用于统计指定分组下出现的次数,
citytype是分组条件

核心在于inner join的的临时表操作,其中使用变量操作追加rownum字段
如果变量citytype值等同于临时表的同名字段则该行数据排序下标row++,否则为1

@city:=city as city , @type:=type as type 表示给每行数据的字段值赋给变量

之后在inner join内联表 之后使用自定义的rownum字段b.rownum<=100进行数量条件的限制即可,最后order by 操作便于查看数据

参考:

https://blog.csdn.net/ylqmf/article/details/39005949

https://blog.csdn.net/woshihaiyong168/article/details/78803655

https://zhidao.baidu.com/question/618263527798895012.html

PEACE~

其他文章:
本文固定链接:https://www.hhtjim.com/mysql-grouping-sorting-limit-problem.html
matrix
本文章由 matrix 于2018年05月03日发布在零零星星分类下,目前没有通告,你可以至底部留下评论。
转载请注明:mysql的分组排序limit问题-HHTjim'S 部落格
关键字:

有1条评论 »

  1. 彩博888 彩博888 2018-7-8 16:57:39 +0800#1

    望来已是几千载,只似当时初望时。

添加新评论 »

 🙈 😱 😂 😛 😭 😳 😀 😆 👿 😉 😯 😮 😕 😎 😐 😥 😡 😈 💡

插入图片

NOTICE: You should type some Chinese word (like “你好”) in your comment to pass the spam-check, thanks for your patience!