php – 根据mySQL中的COUNT()值限制GROUP BY

我正在将事件记录到MysqL数据库中,并希望获得前3个事件用于监视目的.

我的表事件日志如下所示:

+----+------------------+---------------------+
| id |    eventname     |      eventdate      |
+----+------------------+---------------------+
|  0 | machine1.started | 2016-09-04 19:22:23 |
|  1 | machine2.reboot  | 2016-09-04 20:23:11 |
|  2 | machine1.stopped | 2016-09-04 20:24:12 |
|  3 | machine1.started | 2016-09-04 20:25:12 |
|  4 | machine1.stopped | 2016-09-04 23:23:16 |
|  5 | machine0.started | 2016-09-04 23:24:00 |
|  6 | machine1.started | 2016-09-04 23:24:16 |
|  7 | machine3.started | 2016-09-04 23:25:00 |
|  8 | machine4.started | 2016-09-04 23:26:00 |
|  9 | cluster.alive    | 2016-09-04 23:30:00 |
| 10 | cluster.alive    | 2016-09-05 11:30:00 |
+----+------------------+---------------------+

查询最终应返回以下内容,持有

>最常发生的前3个事件(基于MysqL的COUNT()函数生成的列事件计数),按事件名称分组
>只有2行,其中eventcount = 1,但仅当1位于前3个事件计数内时(因为有很多事件发生在
一次,因此会超载我的前端)

基于上表的所需结果示例:

+------------+------------------+
| eventcount |    eventname     |
+------------+------------------+
|          3 | machine1.started |
|          2 | machine1.stopped |
|          2 | cluster.alive    |
|          1 | machine0.started |
|          1 | machine2.started |
+------------+------------------+

请注意,我不需要仅返回3行,而是具有3个最高事件数量的行.

我通过搞乱下面的查询字符串进行了大量的实验,包括多个选择和可疑的CASE … WHEN条件,但是无法使其按照我需要的方式工作.

SELECT COUNT(id) AS 'eventcount',eventname
FROM eventlog
GROUP BY eventname
ORDER BY eventcount DESC;

以高效的方式获得理想结果的最佳方法是什么?

最佳答案
这是使用变量的一种方法
sql小提琴:http://sqlfiddle.com/#!9/b3458b/16

SELECT
  t2.eventcount,t2.eventname
FROM
(
  SELECT
      t.eventname,t.eventcount,@Rank:=IF(@PrevCount=t.eventcount,@Rank,@Rank+1) Rank,@CountRownum:=IF(@PrevCount=t.eventcount,@CountRowNum + 1,1) CountRowNum,@PrevCount:= t.eventcount
    FROM
      (
        SELECT
          l.eventname,COUNT(*) as eventcount
        FROM
          eventlog l
        GROUP BY
          l.eventname
        ORDER BY
          COUNT(*) DESC
      ) t
      CROSS JOIN (SELECT @Rank:=0,@CountRowNum:=0,@PrevCount:=-1) var
    ORDER BY
      t.eventcount DESC
) t2
WHERE
  t2.Rank < 4
  AND NOT (t2.eventcount = 1 AND t2.CountRowNum > 2)

相关文章

优化MySQL数据库发布系统存储的方法有:1.mysql库主从读写分...
使用mysql的方法:在“我的电脑”→右键→“管理”→“服务”...
在mysql中查看root用户权限的方法:1.命令行启动mysql服务;...
MySQL主从复制是用来备份一个与主数据库一样环境的从数据库,...
运行mysql的方法1.启动mysql服务,在“我的电脑”→右键→“...
开启mysql的方法1.可以通过快捷键win+r,输入cmd,打开窗口,...