Home > Database > Mysql Tutorial > body text

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

WBOY
Release: 2016-06-07 15:46:31
Original
1401 people have browsed it

MySQL分组然后取每个分组中按照某些字段排序的topN条数据 建表 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) E

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

建表

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;
Copy after login





插入测试数据


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');
Copy after login






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


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;
Copy after login


结果集如下:

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



注意:

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

二、IFNULL判断很重要,否则MySQL会将下一条数据放进去。如果c列为NULL,则设置一个默认值为0,防止将第四条数据(1)放进去。


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

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


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


如果你有更好的写法,请回复一下,让我知道,谢谢



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!