首页 > 解决方案 > 使用 MAX() 选择未显示预期结果

问题描述

所以我有这张桌子。

 id     header_id   message_from           message         message_date            attachment
    1   0920-0001   USR-0920-0001   MESSAGE ID 1    18/09/2020 04:11    
    3   0920-0001   USR-0920-0001                   18/09/2020 11:15    862db13b42d569b4afe69828736f4ad8.jpg
    4   0920-0001   USR-0920-0001   MESSAGE ID 4    18/09/2020 11:16    
    5   0920-0001   ADMIN           MESSAGE ID 5    18/09/2020 11:16    
    6   0920-0001   ADMIN           MESSAGE ID 6    18/09/2020 11:16    
    7   0920-0002   USR-0920-0001     Hi            18/09/2020 11:52    

我想达到这个结果

    id  header_id   message_from    message         message_date      attachment
     6  0920-0001   ADMIN           MESSAGE ID 6    18/09/2020 11:16    
     7  0920-0002   USR-0920-0001   Hi              18/09/2020 11:52    

我正在尝试使用此查询

SELECT max(id) id , header_id,message from tbl_detail group by header_id

但是这样的结果

id  header_id   message_from    message         message_date      attachment
 6  0920-0001   ADMIN           MESSAGE ID 1    18/09/2020 11:16    
 7  0920-0002   USR-0920-0001   Hi              18/09/2020 11:52    

我错过了什么 ?提前致谢

标签: mysqlsqldatetimegreatest-n-per-groupwindow-functions

解决方案


您的查询一开始是无效的标准 SQL,因为selectandgroup by子句不一致。MySQL 可以容忍这种情况,但不会做你想做的事情(你实际上得到了 column 的任意值message)。

您希望通过以下方式获得最新消息header_id:不要考虑聚合- 而是考虑过滤

select d.*
from tbl_detail d
where d.id = (select max(d1.id) from tbl_detail d1 where d1.header_id = d.header_id)

对于性能,请考虑在(header_id, id desc).

如果您运行的是 MySQL 8.0,也可以使用窗口函数来完成:

select d.*
from (
    select d.*, row_number() over(partition by header_id order by id desc) rn
    from tbl_detail d
) d
where rn = 1

根据您的实际要求,您可能希望使用列message_date而不是对id行进行排序。


推荐阅读