Sql---获取分组数据

按条件取分组内前几条数据

示例

按照资讯分类分组,取每组的前3条资讯信息列表;

CREATE TABLE `info`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `views` int(255) DEFAULT NULL,
  `info_type_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of info
-- ----------------------------
INSERT INTO `info` VALUES (1, '中日海军演习', 10, 4);
INSERT INTO `info` VALUES (2, '美俄军事竞赛', 22, 4);
INSERT INTO `info` VALUES (3, '流浪地球电影大火', 188, 1);
INSERT INTO `info` VALUES (4, '葛优瘫', 99, 2);
INSERT INTO `info` VALUES (5, '周杰伦出轨了', 877, 2);
INSERT INTO `info` VALUES (6, '蔡依林西安演唱会', 86, 1);
INSERT INTO `info` VALUES (7, '中纪委调盐', 67, 3);
INSERT INTO `info` VALUES (8, '人民大会堂', 109, 3);
INSERT INTO `info` VALUES (9, '重庆称为网红城市', 202, 1);
INSERT INTO `info` VALUES (10, '胡歌结婚了', 300, 2);
INSERT INTO `info` VALUES (11, 'ipone15马上上市', 678, 2);
INSERT INTO `info` VALUES (12, '中国探月成功', 54, 4);
INSERT INTO `info` VALUES (13, '钓鱼岛对峙', 67, 4);


CREATE TABLE `info_type`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of info_type
-- ----------------------------
INSERT INTO `info_type` VALUES (1, '娱乐');
INSERT INTO `info_type` VALUES (2, '八卦');
INSERT INTO `info_type` VALUES (3, '政治');
INSERT INTO `info_type` VALUES (4, '军事');

  

解决思路

  GROUP BY 使用的各种方式都不能实现

  使用相关子查询(https://www.cnblogs.com/anpeiyong/p/16714963.html)

  在查询 每条资讯记录时要是能查出其所在类型的排名,然后 根据排名字段进行过滤

  (要计算出 某条资讯信息的 在同资讯分类下所有记录中排第几名,换成算出 有多少条浏览量比当前记录的浏览量高,然后根据具体的多少(N)条+1 就是当前记录所在其分类下的的排名

 

SELECT c.* FROM 
(
    SELECT *,(SELECT COUNT(*)+1 FROM info b WHERE b.info_type_id=a.info_type_id and b.views>a.views) top FROM info a
) c 
WHERE c.top <= 3 
ORDER BY c.info_type_id,c.top

  

结果:

 

posted on 2024-02-21 16:12  anpeiyong  阅读(20)  评论(0编辑  收藏  举报

导航