获取最新的行

时间:2013-06-25 08:38:40

标签: mysql group-by

我正在尝试获取具有指定“拉”值的最新记录,然后按imei编号分组。但是我得到了错误的输出,时间与我的数据库中没有匹配

这是我的表格。

    IMEI              TIME                      STATUS
    354851057191551   2013-06-25 10:11:30       pull getrestbyimei
    354851057191551   2013-06-25 10:10:36       Push getrestbyimei
    354851057234971   2013-06-25 10:10:34       Push getbookings
    351895053436612   2013-06-25 10:10:32       pull getrestbyimei
    351895053436612   2013-06-25 10:10:31       pull getrestbyimei

期望的输出:

        IMEI              TIME                      STATUS
        354851057191551   2013-06-25 10:11:30       pull getrestbyimei
        351895053436612   2013-06-25 10:10:32       pull getrestbyimei

这是我尝试的方式:

SELECT imei as IMEI, MAX(FROM_UNIXTIME(timestamp)) as TIME, action as STATUS
    FROM testlog
    where action like  'pull%'
    GROUP BY imei
order by TIME asc

5 个答案:

答案 0 :(得分:1)

您需要order by TIME desc来检索最新记录

答案 1 :(得分:1)

我认为您不需要FROM_UNIXTIME功能。

SELECT imei as IMEI, MAX(timestamp) as TIME, action as STATUS
    FROM testlog
    where action like  'pull%'
    GROUP BY imei
order by TIME asc

这是SQL Fiddle Demo

答案 2 :(得分:1)

您需要一个子选择来获取每种类型的最新记录时间戳,然后将其连接到表中以获取其余的行列。否则,您获得的操作可能是也可能不是最新操作(如果您有多个不同的操作,但从拉开始)。

SELECT a.imei, a.timestamp, a.action
FROM testlog a
INNER JOIN
(
    SELECT imei as IMEI, MAX(timestamp) as MaxTime
    FROM testlog
    where action like  'pull%'
    GROUP BY imei
) b
ON a.imei = b.imei
AND a.timestamp = b.MaxTime

另一个问题是您的时间戳是时间戳,而不是unix时间戳。所以你不应该从unix时间戳转换它。

答案 3 :(得分:0)

您可以使用ORDER BY PRIMARY_KEY DESC

此处PRIMARY_KEY是您的主要关键字段

答案 4 :(得分:0)

试试这个

   SELECT imei as IMEI, MAX(timestamp) as TIME, action as STATUS
   FROM testlog
   where action like  'pull%'
   GROUP BY imei
   order by TIME asc