首页 > 解决方案 > 如何检索相同数据 ID 的最大值

问题描述

对于我的监控工具 (Centreon),我需要创建一个脚本,该脚本每天都会向我发送一份报告,其中包含已确认 X 天的主机/服务。

为此,我需要在几个表中获取信息,我可以使用以下查询

SELECT DISTINCT     services.host_id,
                        hosts.name,
                        services.service_id,
                        services.description,
                        comments.author,
                        comments.DATA,from_unixtime(comments.entry_time), 
                        comments.comment_id
FROM  services,
        hosts,
        comments 
WHERE services.host_id=hosts.host_id 
        AND hosts.host_id=comments.host_id 
        AND services.acknowledged='1' 
        AND services.enabled='1' 
        AND comments.DATA NOT LIKE '%downtime%'

MySQL查询结果

我需要的是结果只有每个 service_id 的最高 comment_id

有没有办法直接在查询中执行此操作,还是我必须将整个结果导入我的 python 脚本并在之后处理数据?

在此先感谢您的帮助。

标签: mysqlgreatest-n-per-group

解决方案


按结果在组内排序

您可以“ GROUP By ”结果service_id并使用“MAX()”(聚合函数,您也可以使用 Min() )在分组结果中获得最高评论。尝试以下查询:


SELECT services.host_id,
                hosts.name,
                services.service_id,
                services.description,
                comments.author,
                comments.DATA,
                from_unixtime(comments.entry_time), 
                max(comments.comment_id)
FROM services,
     hosts,
     comments 
WHERE services.host_id=hosts.host_id 
  AND hosts.host_id=comments.host_id 
  AND services.acknowledged='1' 
  AND services.enabled='1' 
  AND comments.DATA NOT LIKE '%downtime%'
GROUP By services.service_id
;



推荐阅读