业务要求按照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++,否则为

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

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

参考:

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

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

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

PEACE~

03-04 15:02