原创

MySQL-group by-按字段group by分组 并 返回最新的结果

按 id_employee 分组,并取每个分组的最新的数据。

1、错误:
返回的不是最新的
SELECT employee_name FROM ts_quotation_history WHERE id_quotation_detail =14688907255391191108 AND is_deleted = 0 GROUP BY id_employee ORDER BY pk_id desc, id_employee asc;
2、正确:理解按id_employee 分组
SELECT a.* FROM (SELECT id_employee, max(pk_id) latest_pk_id
-- where 条件都放在这里,仅仅是where条件,分组相关
FROM ts_quotation_history where id_quotation_detail =14688907255391191108 and is_deleted = 0
GROUP BY id_employee ORDER BY pk_id desc -- ORDER BY pk_id desc 这个仅仅是groupby结果进行排序,所以只能用于pk为最新状态的数据(max(pk_id) ),严格模式下(only_full_group_by),ORDER BY pk_id desc 还会报错,业务上max(pk_id) 本身已经是取最新的数据了,那就没有必要ORDER BY pk_id desc 或者是 ORDER BY latest_pk_id desc,如果需要对最终的结果进行排序,应该是放在最后
) b INNER JOIN ts_quotation_history a ON a.id_employee = b.id_employee AND a.pk_id = b.latest_pk_id ;
注意 加黑的 字段关联

严格模式下的only_full_group_by说明
https://blog.csdn.net/afei8080/article/details/129426075
验证测试
show variables like '%sql_mode%';
set session sql_mode='only_full_group_by';
set session sql_mode='';

两个字段分组取最新值也是一样
SELECT h.* FROM (SELECT exam_id,member_id, max(id) latest_pk_id
FROM inp_exam_hand_in_paper where review_status = 2 and is_submit = 1
GROUP BY exam_id,member_id ORDER BY id desc -- ORDER BY pk_id desc 这个仅仅是groupby结果进行排序,所以只能用于pk为最新状态的数据(max(pk_id) ),严格模式下(only_full_group_by),ORDER BY pk_id desc 还会报错,业务上max(pk_id) 本身已经是取最新的数据了,那就没有必要ORDER BY pk_id desc 或者是 ORDER BY latest_pk_id desc,如果需要对最终的结果进行排序,应该是放在最后
) b INNER JOIN inp_exam_hand_in_paper h ON h.exam_id = b.exam_id and h.member_id = b.member_id AND h.id = b.latest_pk_id ;

在此基础上,继续LEFT join到其他表数据:

SELECT h.* FROM (SELECT exam_id,member_id, max(id) latest_pk_id
FROM inp_exam_hand_in_paper where review_status = 2 and is_submit = 1
GROUP BY exam_id,member_id ORDER BY id desc
) b INNER JOIN inp_exam_hand_in_paper h ON h.exam_id = b.exam_id and h.member_id = b.member_id AND h.id = b.latest_pk_id
LEFT JOIN inp_contr_member m on m.id = h.member_id LEFT JOIN inp_contractor c on c.container_id = m.container_id and c.id = m.or_id WHERE h.review_status = 2 and h.is_submit = 1 ; -- 这个where条件是不是放在子查询中跟更好点?提前过滤数据


正文到此结束
本文目录