关于max()/min()和group by 的坑

发布时间 2023-03-27 11:59:18作者: edda_huang

写项目写了 5年一直使用对象性数据,最近又开始使用关系型数据,又回到sql上面的书写了 ,但是昨天遇到 group by 和 max一起使用的问题

实现功能:

目前两张表 一个历史记录表 一个对历史记录的审核表   我需要根据历史记录表中的每一个pointer 字段 group by pointer 后取最新的一条记录 ?

 

 

 

此时我发现historyId 根本不是最大的  也就是说取到的 根本就不是最新的 历史记录.查看相关文档发现

问题根源: group by默认返回每一组的第一条数据(每一组的数据排序都是按默认顺序排序的)

方案探索

那么既然group by默认返回每一组的第一条数据,我们是不是可以先排序再group by呢?

select * from t_ven_all_history where vendorId=2622 and pointerType="Vendor" order by  historyId desc  group by pointer

这种事不符合语法要求的

 

最终方案: 使用子查询的方案解决!

SELECT t.historyId as historyId, t.reason as reason, t.auditlog as auditlog  from (
select  his.historyId as historyId, log.reason as reason, log.auditflag as auditlog ,his.pointer as pointer  FROM  t_ven_all_history his 
left join  t_ven_all_log log  on log.historyId= his.historyId   where his.pointerType='Vendor'   and  his.vendorid=2622 order by his.historyid desc) as t group by t.pointer