项目遇到一个查询需求:
根据 name
值,批量查询出相同 name
下 time
最新的一条数据。折腾了半天发现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)