mysql按某一字段分组取最大(小)值所在行的数据

mysql按某一字段分组取最大(小)值所在行的数据

 

mysql技巧--按某一字段分组取最大(小)值所在行的数据,这是mysql数据库程序员经常用到的在处理一些报表数据时候可以活用!那么猎微网将总结几种mysql查询最大值 mysql查询最小值的方法!

mysql表图如下

mysql按某一字段分组取最大(小)值所在行的数据

具体Php 连接mysql数据库php代码我就不写 下面看select怎么查询

一、按name分组取val最大的值所在行的数据。

--方法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
*/

二、按name分组取val最小的值所在行的数据。

--方法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的第一个值
*/

这种分组方法好像效率不是很高,我用了10000条记录,5个分组实验一下,要70s的查询时间。但对一般可以满足需求的

上一篇:GP中Geoprocessor.Execute(string name, IVariantArray parameters, ITrackCancel trackCancel)


下一篇:使用urllib编写python爬虫