MySQL分組然后取每個分組中按照某些字段排序的topN條數(shù)據(jù)
來源:程序員人生 發(fā)布時間:2014-12-20 08:48:17 閱讀次數(shù):4923次
MySQL分組然后取每一個分組中依照某些字段排序的topN條數(shù)據(jù)
建表
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;
插入測試數(shù)據(jù)
INSERT INTO t(`a`, `b`, `c`, `itime`) VALUES ('1', '1', '1', '2014⑴2-04 19:07:01');
INSERT INTO t(`a`, `b`, `c`, `itime`) VALUES ('1', '1', '2', '2014⑴2-04 19:07:02');
INSERT INTO t (`a`, `b`, `c`, `itime`) VALUES ('1', '1', '3', '2014⑴2-04 19:07:03');
INSERT INTO t (`a`, `b`, `c`, `itime`) VALUES ('1', '1', '4', '2014⑴2-04 19:07:04');
INSERT INTO t(`a`, `b`, `c`, `itime`) VALUES ('1', '2', '1', '2014⑴2-04 19:07:01');
INSERT INTO t (`a`, `b`, `c`, `itime`) VALUES ('1', '2', '2', '2014⑴2-04 19:07:02');
INSERT INTO t(`a`, `b`, `c`, `itime`) VALUES ('1', '2', '3', '2014⑴2-04 19:07:03');
INSERT INTO t (`a`, `b`, `c`, `itime`) VALUES ('1', '2', '4', '2014⑴2-04 19:07:04');
INSERT INTO t(`a`, `b`, `c`, `itime`) VALUES ('1', '2', '5', '2014⑴2-04 19:07:05');
INSERT INTO t (`a`, `b`, `c`, `itime`) VALUES ('1', '2', '6', '2014⑴2-04 19:07:06');
依照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;
結(jié)果集以下:


注意:
1、此方法需要上層利用再做1次處理:上層利用取出結(jié)果集以后,將數(shù)據(jù)依照逗號,再切分成topN份數(shù)據(jù),(注意,有可能有些組沒有topN份數(shù)據(jù))
2、IFNULL判斷很重要,否則MySQL會將下1條數(shù)據(jù)放進(jìn)去。如果c列為NULL,則設(shè)置1個默許值為0,避免將第4條數(shù)據(jù)(1)放進(jìn)去。
下圖是沒有IFNULL的毛病答案:

PS:如果不是萬不得已,沒法實現(xiàn)此功能。不建議在MySQL中使用如此復(fù)雜的SQL語句。
如果你有更好的寫法,請回復(fù)1下,讓我知道,謝謝
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈