mysql分組查詢每組信息的最大值及所有信息


創建測試表及其數據

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for type
-- ----------------------------
DROP TABLE IF EXISTS `type`;
CREATE TABLE `type`  (
  `id` int(11) NOT NULL,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `type` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of type
-- ----------------------------
INSERT INTO `type` VALUES (1, 'a', '1', 19);
INSERT INTO `type` VALUES (2, 'b', '1', 10);
INSERT INTO `type` VALUES (3, 'c', '2', 20);
INSERT INTO `type` VALUES (4, 'd', '2', 30);

SET FOREIGN_KEY_CHECKS = 1;

查詢sql (分析  (select type,max(age) age  from type  GROUP BY type) as ls 先分組查看每組最大的age  (但是name字段無法查看))

然后在作為一個臨時表 關聯type表 加個age關聯字段 確保查看的信息是最大的一條

select  t.* from type  t   join (select type,max(age) age  from type  GROUP BY type) as ls on ls.age=t.age

覺得有用的話 麻煩隨手點贊一下 創作不易 您的點贊 將是我最大的動力 十分感謝!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM