【MySQL】按某一字段分組取最大(小)值所在行的數據

mysql技巧--按某一字段分組取最大(小)值所在行的數據,這是mysql數據庫程序員常常用到的在處理一些報表數據時候能夠活用!那麼微網將總結幾種mysql查詢最大值 mysql查詢最小值的方法!php

mysql表圖以下mysql


具體Php 鏈接mysql數據庫php代碼我就不寫 下面看select怎麼查詢程序員

1、按name分組取val最大的值所在行的數據。sql

--方法1:
select a.* from tb a where val = (select max(val) from tb where name = a.name) order by a.name
--方法2:
select a.* from tb a where not exists(select 1 from tb where name = a.name and val > a.val)
--方法3:
select a.* from tb a,(select name,max(val) val from tb group by name) b where a.name = b.name and a.val = b.val order by a.name
--方法4:
select a.* from tb a inner join (select name , max(val) val from tb group by name) b on a.name = b.name and a.val = b.val order by a.name
--方法5
select a.* from tb a where 1 > (select count(*) from tb where name = a.name and val > a.val ) order by a.name
/*
name       val         memo
---------- ----------- --------------------
a          3           a3:a的第三個值
b          5           b5b5b5b5b5
*/數據庫

2、按name分組取val最小的值所在行的數據。ide

--方法1:
select a.* from tb a where val = (select min(val) from tb where name = a.name) order by a.name
--方法2:
select a.* from tb a where not exists(select 1 from tb where name = a.name and val < a.val)
--方法3:
select a.* from tb a,(select name,min(val) val from tb group by name) b where a.name = b.name and a.val = b.val order by a.name
--方法4:
select a.* from tb a inner join (select name , min(val) val from tb group by name) b on a.name = b.name and a.val = b.val order by a.name
--方法5
select a.* from tb a where 1 > (select count(*) from tb where name = a.name and val < a.val) order by a.name
/*
name       val         memo
---------- ----------- --------------------
a          1           a1--a的第一個值
b          1           b1--b的第一個值
*/spa

這種分組方法好像效率不是很高,我用了10000條記錄,5個分組實驗一下,要70s的查詢時間。但對通常能夠知足需求的。code


原文連接:ci

http://xuliewei.cn/archives/1672get

相關文章
相關標籤/搜索