MySQL对分组记录进行排序

时间:2016-11-11 10:24:34

标签: mysql sql sql-order-by

这是我的包含日志的表:

message                  | data
----------------------------------------------
ttt,tu10=UP,tu20=UP      | 2016-11-11 10:15:05
ttt,tu10=DOWN,tu20=DOWN  | 2016-11-11 10:13:05
ttt,oper=UP,oper2=UP     | 2016-11-11 10:13:01
ttt,oper=DOWN,oper2=DOWN | 2016-11-11 10:07:05
hhh,tu10=UP,tu20=UP      | 2016-11-11 10:05:04
hhh,tu10=DOWN,tu20=DOWN  | 2016-11-11 10:05:01
hhh,tu10=DOWN,tu20=DOWN  | 2016-11-11 09:43:01
hhh,tu10=UP,tu20=UP      | 2016-11-11 09:37:04
hhh,tu10=DOWN,tu20=DOWN  | 2016-11-11 09:35:05
ttt,tu10=DOWN,tu20=DOWN  | 2016-11-11 09:35:01
ttt,tu10=UP,tu20=UP      | 2016-11-11 09:33:05
ttt,tu10=DOWN,tu20=DOWN  | 2016-11-11 05:35:01
hhh,tu10=UP,tu20=UP      | 2016-11-11 05:33:05

我创建了这个查询:

SELECT *
    FROM (
        SELECT 
            *,COUNT(*) AS count
        FROM log
        WHERE data > DATE_SUB(NOW(), INTERVAL 2 HOUR)
        GROUP BY substring_index(message,',',1)
    ) AS tmp
WHERE count > 3

在屏幕上打印:'消息','数据','计数'

获取类似:

ttt,tu10=UP,tu20=UP     | 2016-11-11 09:33:05 | 6
hhh,tu10=DOWN,tu20=DOWN | 2016-11-11 09:35:05 | 5

我想得到第一个,例如:

ttt,tu10=UP,tu20=UP | 2016-11-11 10:15:05 | 6
hhh,tu10=UP,tu20=UP | 2016-11-11 10:05:04 | 5

我尝试了几种排序方式,但我放弃了。

1 个答案:

答案 0 :(得分:0)

我建议您使用substring_index() / group_concat()技巧来实现此目的:

SELECT SUBSTRING_INDEX(GROUP_CONCAT(message ORDER BY data DESC SEPARATOR '|'), '|', 1) as message,
       MAX(data) as data, COUNT(*) AS count
FROM log l
WHERE data > DATE_SUB(NOW(), INTERVAL 2 HOUR)
GROUP BY substring_index(message, ',', 1)
HAVING COUNT(*) >= 3;

请注意GROUP_CONCAT()具有系统变量设置的内部限制,默认值为1,024。如果消息超过该长度,它将生成错误。您可以重置长度。

另一种选择是:

select l.*
from (select substring_index(message, ',', 1) as m1, max(data) as maxd
      from log
      group by substring_index(message, ',', 1)
      having count(*) >= 3
     ) ll join
     l
     on ll.m1 = substring_index(l.message, ',', 1) and ll.maxd = l.data