我们在查询数据时,需要分组后取每组中的最新一条数据(即时间最大的那条),示例如下
复制如下 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
查询结果