MySQL分组而后取每一个分组中按照某些字段排序的topN条数据

MySQL分组而后取每一个分组中按照某些字段排序的topN条数据sql

建表测试

CREATE TABLE `t` (
  `a` int(11) DEFAULT NULL,
  `b` int(11) DEFAULT NULL,
  `c` int(11) DEFAULT NULL,
  `itime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;





插入测试数据


INSERT INTO  t(`a`, `b`, `c`, `itime`) VALUES ('1', '1', '1', '2014-12-04 19:07:01');
INSERT INTO  t(`a`, `b`, `c`, `itime`) VALUES ('1', '1', '2', '2014-12-04 19:07:02');
INSERT INTO t (`a`, `b`, `c`, `itime`) VALUES ('1', '1', '3', '2014-12-04 19:07:03');
INSERT INTO t (`a`, `b`, `c`, `itime`) VALUES ('1', '1', '4', '2014-12-04 19:07:04');
INSERT INTO  t(`a`, `b`, `c`, `itime`) VALUES ('1', '2', '1', '2014-12-04 19:07:01');
INSERT INTO t (`a`, `b`, `c`, `itime`) VALUES ('1', '2', '2', '2014-12-04 19:07:02');
INSERT INTO  t(`a`, `b`, `c`, `itime`) VALUES ('1', '2', '3', '2014-12-04 19:07:03');
INSERT INTO t (`a`, `b`, `c`, `itime`) VALUES ('1', '2', '4', '2014-12-04 19:07:04');
INSERT INTO  t(`a`, `b`, `c`, `itime`) VALUES ('1', '2', '5', '2014-12-04 19:07:05');
INSERT INTO t (`a`, `b`, `c`, `itime`) VALUES ('1', '2', '6', '2014-12-04 19:07:06');






按照a,b分组,而且按照itime字段倒叙排列,取每组的top3spa


SELECT
	t.a,
  	t.b,
	substring_index(
		group_concat(
			IFNULL(t.c,0)
			ORDER BY
				t.itime DESC
		),
		",",
		3
	) c,
	substring_index(
		group_concat(
			t.itime
			ORDER BY
				t.itime DESC
		),
		",",
		3
	) time
FROM
	t t
GROUP BY
	t.a ,t.b;


结果集以下:




注意:3d

1、此方法须要上层应用再作一次处理:上层应用取出结果集之后,将数据按照逗号,再切分红topN份数据,(注意,有可能有些组没有topN份数据)code

2、IFNULL判断很重要,不然MySQL会将下一条数据放进去。若是c列为NULL,则设置一个默认值为0,防止将第四条数据(1)放进去。blog


       下图是没有IFNULL的错误答案:排序


PS:若是不是万不得已,没法实现此功能。不建议在MySQL中使用如此复杂的SQL语句。string


若是你有更好的写法,请回复一下,让我知道,谢谢it