MySQL分组并取每组中create_time字段的最大值, 及这条记录的所有值(理解groupId, 很容易误导)

invest_order_code 排查单号

求获取排查单号相同数大于1的排查单号

SELECT invest_order_code FROM t_invest_order GROUP BY invest_order_code HAVING COUNT(invest_order_code)>1

求排查单未PC20190429092529981636,且id最大的那个id

错误写法: 

SELECT invest_order_code,MAX(id),id FROM t_invest_order WHERE invest_order_code='PC20190429092529981636' GROUP BY invest_order_code

 注意: 会发现两个id不一样, 也就是说,这种写法只能求出每组数据中最大id的那个字段值是多少, 不能求出哪一行所有数据的值. 

如果求那行所有数据的值, 需要进行手动关联查询

SELECT 
    t1.*
FROM t_invest_order t1
INNER JOIN
(
    SELECT 
        invest_order_code,
        MAX(id) AS maxId,
        id AS anyId
    FROM t_invest_order 
    WHERE invest_order_code='PC20190429092529981636' 
    GROUP BY invest_order_code
) t2 ON t1.id=t2.maxId
原文地址:https://www.cnblogs.com/smileblogs/p/11598947.html