mysql分組后如何獲取每個組的第一條數(shù)據(jù)
mysql分組后獲取每個組的第一條數(shù)據(jù)
已知:subject表(主題表),主題表為樹形表
path字段,使用分隔符###,將主題編碼從一級到本級主題編碼,拼接起來,便于查詢主題下子主題數(shù)據(jù)。
現(xiàn)在,需要根據(jù)path排序,聚合查詢一級主題的名稱和條數(shù)。
直接上結(jié)果:
兩種寫法:
一:內(nèi)層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 ;
二:內(nèi)層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 ;
解釋一下:
直接查詢是查不出想要的結(jié)果的,需要嵌套子查詢。但是只嵌套只查詢也是有問題的,內(nèi)層循環(huán)也需要進行過濾一下,可以使用distinct或者group ,再聯(lián)合order by 進行排序,才能獲取想要的結(jié)果。
這樣寫,發(fā)現(xiàn)一個問題,就是如果只有子主題的話,就查不出來一級主題了,改進如下:(多關(guān)聯(lián)一遍,這樣子查詢都省了)
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次重復(fù), last_patient表中某一重復(fù)字段名稱 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
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
MYSQL數(shù)據(jù)庫Innodb?引擎mvcc鎖實現(xiàn)原理
這篇文章主要介紹了MYSQL數(shù)據(jù)庫Innodb?引擎mvcc鎖實現(xiàn)原理,但是mvcc?的實現(xiàn)原理是什么呢?下文我們就來實例說明來mvcc?的實現(xiàn)原理,感興趣的小伙伴可以參考一下2022-05-05Mysql數(shù)據(jù)庫之Binlog日志使用總結(jié)(必看篇)
下面小編就為大家?guī)硪黄狹ysql數(shù)據(jù)庫之Binlog日志使用總結(jié)(必看篇)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-03-03mysql分表分庫的應(yīng)用場景和設(shè)計方式
為大家講述一下在mysql在什么到時候需要進行分表分庫,以及現(xiàn)實的設(shè)計方式。2017-11-11