MySQL分組然後取每個分組中按照某些欄位排序的topN條資料

來源:互聯網
上載者:User

標籤:sql   mysql   分組取每組的topn   group by   group_concat   

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-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欄位倒敘排列,取每組的top3


SELECTt.a,  t.b,substring_index(group_concat(IFNULL(t.c,0)ORDER BYt.itime DESC),",",3) c,substring_index(group_concat(t.itimeORDER BYt.itime DESC),",",3) timeFROMt tGROUP BYt.a ,t.b;


結果集如下:




注意:

一、此方法需要上層應用再做一次處理:上層應用取出結果集以後,將資料按照逗號,再切分成topN份資料,(注意,有可能有些組沒有topN份資料)

二、IFNULL判斷很重要,否則MySQL會將下一條資料放進去。如果c列為NULL,則設定一個預設值為0,防止將第四條資料(1)放進去。


       是沒有IFNULL的錯誤答案:


PS:如果不是萬不得已,無法實現此功能。不建議在MySQL中使用如此複雜的SQL語句。


如果你有更好的寫法,請回複一下,讓我知道,謝謝



MySQL分組然後取每個分組中按照某些欄位排序的topN條資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.