从MySQL中选择最后一个条目的第二个

时间:2015-08-13 10:06:09

标签: mysql

问题:在指定时间段内从每个不同的故障单中的最后一个条目需要第二个

示例数据

ticketTB
ticket createdate          status
111    2015-08-13 04:05:12 good
111    2015-08-13 04:04:12 bad
111    2015-08-13 04:03:12 good
115    2015-08-13 03:05:12 good
115    2015-08-13 03:04:12 bad
115    2015-08-13 03:03:12 good

查询

SELECT ticket, status, createdate FROM ticketTB GROUP BY ticket ORDER BY createdate DESC LIMIT 1,1;

此查询提取:

ticket createdate          status
111    2015-08-13 04:04:12 bad

然而,添加许多其他门票,它只会从我需要的所有门票中扣除第二张,以评估每张不同的门票。

我希望我的查询返回:

ticket createdate          status
111    2015-08-13 04:04:12 bad
115    2015-08-13 03:04:12 bad

2 个答案:

答案 0 :(得分:2)

DROP TABLE IF EXISTS ticketTB;

CREATE TABLE ticketTB
(ticket INT NOT NULL
,createdate DATETIME NOT NULL
,status VARCHAR(12)
,PRIMARY KEY(ticket,createdate)
);

INSERT INTO ticketTB VALUES
(111    ,'2015-08-13 04:05:12','good'),
(111    ,'2015-08-13 04:04:12','bad'),
(111    ,'2015-08-13 04:03:12','good'),
(111    ,'2015-08-13 04:02:12','good'),
(115    ,'2015-08-13 03:05:12','good'),
(115    ,'2015-08-13 03:04:12','bad'),
(115    ,'2015-08-13 03:03:12','good'),
(115    ,'2015-08-13 03:02:12','good');

SELECT * FROM ticketTB;
+--------+---------------------+--------+
| ticket | createdate          | status |
+--------+---------------------+--------+
|    111 | 2015-08-13 04:02:12 | good   |
|    111 | 2015-08-13 04:03:12 | good   |
|    111 | 2015-08-13 04:04:12 | bad    |
|    111 | 2015-08-13 04:05:12 | good   |
|    115 | 2015-08-13 03:02:12 | good   |
|    115 | 2015-08-13 03:03:12 | good   |
|    115 | 2015-08-13 03:04:12 | bad    |
|    115 | 2015-08-13 03:05:12 | good   |
+--------+---------------------+--------+

SELECT x.* 
  FROM ticketTB x 
  JOIN ticketTB y 
    ON y.ticket = x.ticket 
   AND y.createdate >= x.createdate 
 GROUP 
    BY ticket
     , createdate 
HAVING COUNT(*) = 2;
+--------+---------------------+--------+
| ticket | createdate          | status |
+--------+---------------------+--------+
|    111 | 2015-08-13 04:04:12 | bad    |
|    115 | 2015-08-13 03:04:12 | bad    |
+--------+---------------------+--------+

类似下面的方法通常会更快,特别是在较大的数据集上......

SELECT ticket
     , createdate
     , status 
  FROM
     ( SELECT *
            , CASE WHEN @prev = ticket THEN @i:=@i+1 ELSE @i:=1 END rank
            , @prev := ticket prev 
         FROM ticketTB
            , (SELECT @prev:='',@i:=1) vars 
        ORDER 
           BY ticket
            , createdate DESC
     ) x 
 WHERE rank = 2;
+--------+---------------------+--------+
| ticket | createdate          | status |
+--------+---------------------+--------+
|    111 | 2015-08-13 04:04:12 | bad    |
|    115 | 2015-08-13 03:04:12 | bad    |
+--------+---------------------+--------+

答案 1 :(得分:0)

试试这个:

SELECT * FROM my_table ORDER BY rating DESC LIMIT 2,1