某一字段分组取最大(小)值所在行的数据
【mysql技巧】按某一字段分组取最大(小)值所在行的数据
https://blog.csdn.net/zimuxin/article/details/52230662
mysql技巧--按某一字段分组取最大(小)值所在行的数据,这是mysql数据库程序员经常用到的在处理一些报表数据时候可以活用!那么猎微网将总结几种mysql查询最大值 mysql查询最小值的方法!
mysql表图如下
一、按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的查询时间。但对一般可以满足需求的。
SELECT
a.payRcvConfirmedID,
a.StrongRelationID,
a.balance as orgPayments,
b.strongRelationType as type,
e.userID AS payUserId,
e.realName AS payName,
e.orgType AS payType,
f.userID AS recUserId,
f.realName AS recName,
f.orgType AS recType
FROM payrecdb.dt_payrcvconfirmed a
LEFT JOIN payrecdb.dt_strongrelation b ON a.StrongRelationID=b.strongRelationID
LEFT JOIN payrecdb.dt_user e ON b.payOrRelUserID = e.userID
LEFT JOIN payrecdb.dt_user f ON b.rcvOrRelUserID = f.userID
WHERE payRcvConfirmedID = (SELECT max(payRcvConfirmedID) FROM payrecdb.dt_payrcvconfirmed h WHERE h.strongRelationID=a.StrongRelationID) ;