mysql分组后如何获取每个组的第一条数据
作者:Xu_jesse
这篇文章主要介绍了mysql分组后如何获取每个组的第一条数据问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
mysql分组后获取每个组的第一条数据
已知:subject表(主题表),主题表为树形表
path字段,使用分隔符###,将主题编码从一级到本级主题编码,拼接起来,便于查询主题下子主题数据。
现在,需要根据path排序,聚合查询一级主题的名称和条数。
直接上结果:
两种写法:
一:内层distinct
select tt.name as subjectName,path,count(*) as countNum from (select **distinct t.table_id_**, t.SUBJECT_ID_, s.name_ as name,path_,SUBSTRING_INDEX(path_,'###',1) as path from model_table t join hdgp_standard_subject s on t.SUBJECT_ID_ = s.id_ where t.IS_DELETE_ = 0 and !isnull(t.SUBJECT_ID_) and t.VERSION_TYPE_ = 'formal' order by s.path_ ) tt group by tt.path ;
二:内层group
select tt.name as subjectName,path,count(*) as countNum from (select t.SUBJECT_ID_, s.name_ as name,path_,SUBSTRING_INDEX(path_,'###',1) as path from model_table t join hdgp_standard_subject s on t.SUBJECT_ID_ = s.id_ where t.IS_DELETE_ = 0 and !isnull(t.SUBJECT_ID_) and t.VERSION_TYPE_ = 'formal' **group by t.table_id_** order by s.path_ ) tt group by tt.path ;
解释一下:
直接查询是查不出想要的结果的,需要嵌套子查询。但是只嵌套只查询也是有问题的,内层循环也需要进行过滤一下,可以使用distinct或者group ,再联合order by 进行排序,才能获取想要的结果。
这样写,发现一个问题,就是如果只有子主题的话,就查不出来一级主题了,改进如下:(多关联一遍,这样子查询都省了)
SELECT ss.NAME_ AS subjectName, count(*) AS countNum FROM model_table t JOIN hdgp_standard_subject s ON t.SUBJECT_ID_ = s.id_ JOIN hdgp_standard_subject ss ON SUBSTRING_INDEX( s.path_, '###', 1 ) = ss.CODE_ WHERE t.IS_DELETE_ = 0 AND ! isnull( t.SUBJECT_ID_ ) AND t.VERSION_TYPE_ = 'formal' GROUP BY ss.code_
mysql获取每组的第二条记录
-- rank 第n次重复, last_patient表中某一重复字段名称 SELECT t.id,t.patient_id,t.patient_name FROM ( select id,patient_id,patient_name, if(@last_patient = a.patient_id,@rank := @rank+1,@rank := 1) AS "rank", -- 判断 当前patient_id与@last_patient是否相等,不相等rank为1,相等时rank加1, @last_patient := a.patient_id FROM lis_data_collection a,(SELECT @rank:=0,@last_patient:="") r -- 声明两个变量@rnak及@last_patient,并初始化 ORDER BY a.id asc ) t where rank= 2 ORDER BY id ASC
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。