Heim > Datenbank > MySQL-Tutorial > Hauptteil

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

WBOY
Freigeben: 2016-06-07 15:46:31
Original
1361 Leute haben es durchsucht

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;
Nach dem Login kopieren





插入测试数据


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');
Nach dem Login kopieren






按照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;
Nach dem Login kopieren


结果集如下:

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



注意:

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

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


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

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


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


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



Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!