MySQL分組然后取每個分組中按照某些字段排序的topN條數據
來源:程序員人生 發(fā)布時間:2014-12-20 08:48:17 閱讀次數:4915次
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;
插入測試數據
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;
結果集以下:


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

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