Sorting and grouping the group MySql

Table is as follows:

TABLE `asset_change_log` the CREATE (
  ` id` int (. 11) the AUTO_INCREMENT the COMMENT unsigned the NOT NULL 'ID',
  `asset_id` int (. 11) the COMMENT unsigned the NOT NULL 'Asset ID',
  ` status` tinyint (. 1) the NOT NULL the DEFAULT unsigned ' 0 'COMMENT' state storage 1 2 3 library to return lent 4 ',
  `ctime` the NOT NULL the DEFAULT CURRENT_TIMESTAMP the COMMENT datetime' created ',
  a PRIMARY KEY (` id`)
) = ENGINE the InnoDB the DEFAULT the CHARSET = utf8mb4

 

You need to check out this table the final status of each asset.

SQL as follows:

SELECT a.* FROM `asset_change_log` AS a RIGHT JOIN
(SELECT asset_id, MAX(ctime) AS maxtime FROM `asset_change_log` GROUP BY asset_id) AS b
ON a.asset_id=b.asset_id AND b.maxtime=a.`ctime` ORDER BY a.asset_id ASC;

 

Need some attention:

Want to get the final status of each asset can take the maximum time (insert record time).

After the maximum time to get some use out of condition. Otherwise there is no way to match the last record of a particular asset.

 

 

 

Guess you like

Origin www.cnblogs.com/liuqd001/p/11840904.html