关于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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2020-03-27 innodb和myisam对比及索引原理区别