场景描述:接手离职同事的一行代码,如下:
select pdtm.name,pdtm.temperature,pdtm.humidity,pdtm.pressure from (
select pp.id,p.name,pp.temperature,pp.humidity,pp.pressure from phe_device_thermo_mst
p LEFT JOIN phe_device_thermo_result_mst pp on p.id = pp.phe_device_thermo_mst_id group by p.id order by pp.create_time desc) pdtm
group by pdtm.name
需求:查询每台设备的最新一条数据
这条sql的实现是通过分组的方式实现的,思路就是按创建时间倒序,再分组获得其中的第一条,也就是最新一条数据了。
但是,在mysql的5.7之后,group by的子查询包含order by的话,假如order by不与limit一起使用的话,order by 会被忽略不生效
解决方案:在order by后面加上limit 条数。
select pdtm.name,pdtm.temperature,pdtm.humidity,pdtm.pressure from(select pp.id,p.name,pp.temperature,pp.humidity,pp.pressure from phe_device_thermo_mst pLEFT JOIN phe_device_thermo_result_mst pp on p.id = pp.phe_device_thermo_mst_idwhere p.lifecycle = 'released'and pp.lifecycle = 'released'and p.is_delete = 'no'and pp.is_delete = 'no'order by pp.create_time desclimit #{count} ) pdtm group by pdtm.name