Mysql先排序后分组简单方法
mysql常见的排序分组是使用子查询先排序再分组,我们来用另外一种方式实现简单的分组排序
CREATE TABLE `user` (
`u_id` int(11) NOT NULL AUTO_INCREMENT,
`u_name` varchar(50) NOT NULL,
`u_age` tinyint(3) unsigned NOT NULL,
`u_gender` char(1) NOT NULL,
`u_add_time` int(11) DEFAULT NULL,
PRIMARY KEY (`u_id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 COMMENT='用户';
insert into `user`(u_name,u_age,u_gender,u_add_time) VALUES('张三','18','男',UNIX_TIMESTAMP(NOW()));
insert into `user`(u_name,u_age,u_gender,u_add_time) VALUES('马七','16','男',UNIX_TIMESTAMP(NOW()));
insert into `user`(u_name,u_age,u_gender,u_add_time) VALUES('李四','18','女',UNIX_TIMESTAMP(NOW()));
insert into `user`(u_name,u_age,u_gender,u_add_time) VALUES('王六','17','女',UNIX_TIMESTAMP(NOW()));
insert into `user`(u_name,u_age,u_gender,u_add_time) VALUES('刘五','17','男',UNIX_TIMESTAMP(NOW()));
insert into `user`(u_name,u_age,u_gender,u_add_time) VALUES('周十','16','女',UNIX_TIMESTAMP(NOW()));
select SUBSTRING_INDEX(GROUP_CONCAT(u_name order by u_age desc),',',1) as username from `user` group by u_gender
方法二
要求:mysql版本>=8.0
select u_name,sorts from (select u_name,dense_rank() over(partition by u_gender order by u_age desc) as sorts from `user`) as m where sorts = 1
注意:
函数SUBSTRING_INDEX(str, delimiter, count) 返回一个 str 的子字符串,在 delimiter 出现 count 次的位置截取。 如果 count > 0,从则左边数起,且返回位置前的子串; 如果 count < 0,从则右边数起,且返回位置后的子串。