1. 程式人生 > 資料庫 >mysql 分組取最大時間(分組取最新資料)

mysql 分組取最大時間(分組取最新資料)

在查詢資料時,需要分組後取每組中的最新一條資料(即時間最大的那條),示例如下
複製如下 sql 語句建表,新增資料

SET FOREIGN_KEY_CHECKS=0;
 
-- ----------------------------
-- Table structure for t_company
-- ----------------------------
DROP TABLE IF EXISTS `t_company`;
CREATE TABLE `t_company` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `company_name` varchar(40) DEFAULT NULL,
  `type` int(255) DEFAULT NULL,
  `create_date` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
 
-- ----------------------------
-- Records of t_company
-- ----------------------------
INSERT INTO `t_company` VALUES ('1', '騰訊', '1', '2019-01-08 15:44:55');
INSERT INTO `t_company` VALUES ('2', '阿里巴巴', '1', '2019-01-09 15:47:08');
INSERT INTO `t_company` VALUES ('3', '百度', '1', '2019-01-10 15:47:14');
INSERT INTO `t_company` VALUES ('4', '小米', '0', '2019-01-11 15:47:19');
INSERT INTO `t_company` VALUES ('5', '華為', '0', '2019-01-17 15:47:23');
INSERT INTO `t_company` VALUES ('6', '農業銀行', '2', '2019-01-29 15:47:29');
INSERT INTO `t_company` VALUES ('7', '工商銀行', '2', '2019-01-24 15:47:32');
INSERT INTO `t_company` VALUES ('8', '興業銀行', '2', '2019-08-21 17:48:38');
INSERT INTO `t_company` VALUES ('9', '浦發銀行', '2', '2019-08-21 17:48:38');
INSERT INTO `t_company` VALUES ('10', '貴州茅臺', '0', '2019-08-21 17:48:38');
INSERT INTO `t_company` VALUES ('11', '民生銀行', '2', '2019-01-10 15:47:14');

建表如下
在這裡插入圖片描述

查詢思路: 先分組使用 max() 函式查詢出每組中最大的時間和型別,將時間欄位和型別欄位定義為一個新表 tmp,再通過與 tmp 表的時間和型別聯合查詢,即可查詢出每組中的最新一條資料(時間最大的那條資料)。之所以要使用時間和型別兩個欄位,是因為可能存在不同型別但時間相同的資料

sql 語句如下

select * from t_company t RIGHT JOIN 
(select type, MAX(create_date) as "createDate" from t_company GROUP BY type) tmp 
on t.create_date = tmp.createDate and t.type=tmp.type

在這裡插入圖片描述