MySQL 分组后取每组ID最大的行

前言

在工作中有需要用到分组后查询最大id的场景,这里举个例子进行记录一下

表结构及插入数据

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
DROP TABLE IF EXISTS `listings`;

CREATE TABLE `listings` (
  `store_id` int(11) DEFAULT NULL,
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

LOCK TABLES `listings` WRITE;
/*!40000 ALTER TABLE `listings` DISABLE KEYS */;

INSERT INTO `listings` (`store_id`, `id`, `product_id`)
VALUES
	(3,1,1),
	(3,2,2),
	(3,3,1),
	(3,4,1),
	(3,5,2);

/*!40000 ALTER TABLE `listings` ENABLE KEYS */;
UNLOCK TABLES;

查看表数据

1
select product_id, store_id, id from listings;

表中数据

查询store id 为3,product_id 分别为1和2里ID最大的行数据

1
select product_id,store_id,max(id) id from listings where product_id in (1,2) and store_id = 3 group by product_id;

查询结果