sql语句先分组,再获取每组最新的一条数据

错误写法:

SELECT
	a.area_name,
	c.collector_code,
	c.install_position,
	c.update_time,
	c.update_user,
	c.description,
	r.platform_time,
	r.voltage,
	r.csq,
	r.rsrp 
FROM
	device_watermeter w
	INNER JOIN device_collector c ON w.collector_id = c.id
	INNER JOIN data_area a ON a.id = w.area_id
	LEFT JOIN data_meter_latest_reading r ON r.meter_id = w.id 
WHERE
	c.company_id = 12 
	AND c.collector_category = 1 
GROUP BY
	c.collector_code 
ORDER BY
	r.platform_time DESC 
	LIMIT 1

正确写法:

SELECT
	a.area_name,
	c.collector_code,
	c.install_position,
	c.update_time,
	c.update_user,
	c.description,
	r.platform_time,
	r.voltage,
	r.csq,
	r.rsrp
FROM
	device_collector c
	LEFT JOIN (SELECT * FROM data_meter_latest_reading ORDER BY platform_time DESC LIMIT 100000) r ON r.collector_id = c.id
	LEFT JOIN data_area a ON a.id = r.area_id 
WHERE
	c.company_id = 12 
	AND c.collector_category=1
GROUP BY
	c.collector_code 

你可能感兴趣的:(db,sql,数据库)