Mysql分组查询每组最新的一条数据

在工作中遇到一个问题,需要查出每个公司最新的那条数据。

所以需根据公司进行分组: 

未进行分组时:

select a.id, b.name companyName, result_asset ,result_liability ,result_net_asset, a.create_time ,a.is_deleted 
from bus_property_appraisal_approve a
join bas_company b on a.company_id = b.id 
where a.is_deleted = 0 and b.is_deleted = 0 and a.status > 0

Mysql分组查询每组最新的一条数据_第1张图片

分组查询后:  

select a.id, b.name companyName, result_asset ,result_liability ,result_net_asset
from bus_property_appraisal_approve a
join bas_company b on a.company_id = b.id 
join (select MAX(id) as id from bus_property_appraisal_approve where is_deleted = 0 and status > 0 group by company_id) c on a.id = c.id
where a.is_deleted = 0 and b.is_deleted = 0 and a.status > 0
order by result_asset

Mysql分组查询每组最新的一条数据_第2张图片

简化一下sql语句:

SELECT
	t1.* 
FROM
	customer_wallet_detail t1
	INNER JOIN ( SELECT MAX( id ) AS id FROM customer_wallet_detail GROUP BY customer_id ) t2 
    ON t1.id = t2.id

 

参考文章:

Mysql分组查询每组最新的一条数据(五种实现方法)_mysql group by 取最新的一条_kerwin_code的博客-CSDN博客

你可能感兴趣的:(MySQL,mysql,数据库)