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

写项目写了 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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值