MySQL group and then create the CREATETABLE 'T' ('A' int (11) DEFAULTNULL, 'B' int (11) DEFAULTNULL, 'C' int (11) DEFAULTNULL, 'itime' timestampNOTNULLDEFAULTCURRENT _ TIMESTAMPONUPDATECURRENT_TIMESTAMP) E
MySQL group and 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 group then obtains the Top N pieces of data sorted by certain fields in each group.
Create a table
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 Test Data
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');
Group by a and B, and sort by itime field in reverse order.
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;
The result set is as follows:
Note:
1. This method requires the upper-layer application to perform another processing: After the upper-layer application extracts the result set, it splits the data into the top N parts based on commas (,). (Note, some groups may not have Top N data)
Ii. IFNULL judgment is very important, otherwise MySQL will put the next data in. If column c is NULL, a default value of 0 is set to prevent the fourth data (1) from being put in.
Is the incorrect answer without IFNULL:
PS: if it is not a last resort, this function cannot be implemented. It is not recommended to use such complex SQL statements in MySQL.
If you have a better way of writing, please reply and let me know. Thank you.