项目遇到一个查询需求:

根据 name值,批量查询出相同 nametime最新的一条数据。折腾了半天发现mysql有top1查询方法。

查出所有数据

top1方法

select name,time,price from items a where time=(select max(time) from items where a.tid = items.tid)

join方法:

SELECT a.* FROM items a JOIN (SELECT MAX(a.time) as time,a.tid FROM items a GROUP BY a.name) b on a.name = b.name AND a.time = b.time

查出指定多个name下的数据

指定name 11,55,多个逗号分开

SELECT a.id,a.name,a.type,a.time FROM demo a
JOIN (SELECT MAX(a.time) as time,a.tid
FROM demo a 
GROUP BY a.name) b on a.name = b.name AND a.time = b.time
where a.tid in(11,55)
最后修改于:2021-10-24 09:43
文章链接: https://oct.cn/view/106
版权声明: 本站所有文章除特别声明外。转载请注明来自 十月笔记