mysql - 如何检索相同数据 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%'
我需要的是结果只有每个 service_id 的最高 comment_id
有没有办法直接在查询中执行此操作,还是我必须将整个结果导入我的 python 脚本并在之后处理数据?
在此先感谢您的帮助。
解决方案
按结果在组内排序
您可以“ 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
;
推荐阅读
- java - 如何在arraylist中显示重复数
- php - 为什么我收到错误致命错误:在非对象上调用成员函数 getUserOptions()
- format - 是否有标准化的消息格式?
- java - 如何避免并发重复查询
- python - 使用内置函数从另一个类返回矩形集合
- karaf - 将ODL控制器连接到mininet时,为什么在dlux.topology页面看不到拓扑信息?
- laravel - 在 QueryBuilder 中使用 Where - Laravel
- node.js - 在没有 npm 或 node.js 的情况下将 Angular Universal 部署到共享主机
- android - 当我添加一个新的 .c 文件时,Android Studio 通知我它不是项目的一部分
- sql - 需要编写一个存储过程来从 SQL hive 中的 yymmddhhmmss 类型时间戳中提取小时数