美文网首页
MySQL 分组后取每组ID最大的行

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

作者: 夏依旧微凉啊 | 来源:发表于2019-07-10 18:55 被阅读0次

1、表结构及插入数据

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;

2、查看表数据

select product_id, store_id, id from listings;
表中数据

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

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

相关文章

网友评论

      本文标题:MySQL 分组后取每组ID最大的行

      本文链接:https://www.haomeiwen.com/subject/zrdkkctx.html