Mysql函式
阿新 • • 發佈:2020-09-16
一,列表分組之後查詢所有組內某一個時間欄位最大的資料
ContractEndDate :某一個時間欄位
RECORDID:表ID
SELECT A.* from (select * from (SELECT * FROM hrm_contract order by ContractEndDate DESC limit 10000) a GROUP BY a.A00) B
left join hrm_contract A on a.RECORDID=b.RECORDID
二,多級選單表根據parent_id查詢包括父節點在內的所有子節點id
SELECT * FROM ( SELECT t1.id,IF(FIND_IN_SET(t1.parent_id,@pids)>0,@pids:=CONCAT(@pids,',',id),0) as ischild FROM ( SELECT * FROM menu ORDER BY parent_id ) t1,(SELECT @pids:=1) t2 UNION SELECT dd.id ,dd.id as ischild FROM menu as dd WHERE dd.id=1 ) cc WHERE cc.ischild <> 0
三,多級選單表根據子節點id查詢包括子節點在內的所有父節點parent_id
表結構
查詢sql
SELECT T2.id FROM ( SELECT @r AS _id, (SELECT @r := parent_id FROM user WHERE id = _id) AS parent_id, @l := @l + 1 AS lvl FROM (SELECT @r := 7, @l := 0) vars, -- 查詢id為5的所有上級 user h WHERE @r <> 0) T1 JOIN user T2 ON T1._id = T2.id ORDER BY T1.lvl DESC
查詢結果
四,group by 對多個欄位進行分組
group by 欄位一:將所有具有相同欄位一的記錄放到一個分組裡
group by 欄位一,欄位二 :將所有具有相同欄位一和欄位二的記錄放到一個分組裡
五,Case When和聚合函式count、sum的使用
根據貧困標誌,取出不同標準下的的人數有多少,以區縣位單位。
1代表已脫貧人口;2代表返貧人口;3代表未脫貧
select t3.region_id as 'regionId', t3.region_name as 'regionName', count(case when t1.tricolor = 1 then 1 else null end ) as 'greenTotal', count(case when t1.tricolor = 2 then 1 else null end ) as 'yellowTotal', count(case when t1.tricolor = 3 then 1 else null end )as 'redTotal' from pa_household_member t1 left join pa_household t2 on t2.household_id = t1.household_id left join system_region t3 on t3.region_id = t2.area group by t2.area
count(1) 算上一條記錄 count(null)為0;利用此特性進行分類統計。不用寫複雜的子查詢。count在套住case when ..... 例如: count (case when ....end )