mysql子查询排序问题解决
问题:
想要实现同一用户同一产品只显示时间最新的记录,但在使用子查询排序后,结果却不正确。
回答:
由于使用的数据库版本是5.7,无法使用窗口函数来实现此需求。下面提供一个版本兼容的解决方案:
子查询关联
首先,使用子查询计算每个分组(user_id、product_id)的 create_time最大值。接着,将该子查询与原表关联,条件为 user_id、product_id 相等,且 create_time 为最大值。
改进后的sql语句:
select t2.id, t1.* from ( select max(create_time) as create_time, user_id, product_id from demo group by user_id, product_id ) t1 left join demo t2 on t1.user_id = t2.user_id and t1.product_id = t2.product_id and t1.create_time = t2.create_time
解释:
以上就是MySQL 5.7 子查询排序:如何获取同一用户同一产品时间最新的记录?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号