mysql - 使用 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
我错过了什么 ?提前致谢
解决方案
您的查询一开始是无效的标准 SQL,因为select
andgroup 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
行进行排序。
推荐阅读
- sql-server - 如何在 Entity Framework Core 中使用 FromSql 将值列表作为 Sql 参数传递
- c++ - 使用 STL 的简单视图
- amp-html - 将 GDPR 同意字符串传递到 amp-iframe
- bixby - 下一个/上一个音频的对话驱动程序
- angular - 如何从角度中的地址获取经度和纬度 - 离子4
- go - 如何在该 `struct` 切片的新`type` 中访问`struct` 的字段?
- generics - Kotlin 强制参数类型为字符串、布尔值或数字
- javascript - “(事件:字符串)=> void”类型的参数不可分配给“EventListenerOrEventListenerObject”类型的参数
- c# - 使用正确凭据的无效登录尝试 ASP.NET 身份
- sql - SQL 'Like' 函数 - 澄清