mysql 分组、排序
业务场景:获取每个审核环节中,最后一次审核时,对应的审核人、审核日期;
第一步 获取当前任务的审核记录,以group by AUDIT_FLAG_NAME分组后 通过 group_concat 进行指定字段的排序拼接,然后通过SUBSTRING_INDEX 来查找指定下标的数据,实现了快速的定位分组数据
SELECT
audit.AUDIT_FLAG_NAME,
SUBSTRING_INDEX(GROUP_CONCAT(audit.id ORDER BY audit.CREATE_DATE DESC, ',' ), ',', 1 ) AS keyId
FROM
dailymanageaudit audit
WHERE
audit.IS_DEL = 0
AND audit.DAILY_MANAGE_ID = '328'
GROUP BY
audit.AUDIT_FLAG_NAME
第二步 用上面的查询结果,连表查询即可
select dt.CREATE_DATE createDate,user.realName,dt.AUDIT_FLAG_NAME auditFlagName from (
SELECT
audit.AUDIT_FLAG_NAME,
SUBSTRING_INDEX(GROUP_CONCAT(audit.id ORDER BY audit.CREATE_DATE DESC, ',' ), ',', 1 ) AS keyId
FROM
dailymanageaudit audit
WHERE
audit.IS_DEL = 0
AND audit.DAILY_MANAGE_ID = '328'
GROUP BY
audit.AUDIT_FLAG_NAME
) tab
left join dailymanageaudit dt on tab.keyId = dt.id
left join sysuser user on user.id = dt.SYS_USER_ID
结果如下: