如何选择日期之间差异最大的列 - MySQL

时间:2015-05-25 11:18:52

标签: mysql sql database

我正在尝试找到该行的产品EPC,其在第一次和最后一次读取之间的时间最长。表中可以有多个条目。

无论我做什么,我似乎无法弄清楚如何获取此信息。

这是表格:

CREATE TABLE IF NOT EXISTS `Track_Record` (
  `longitude` varchar(15) NOT NULL ,
  `lattitude` varchar(15) NOT NULL ,
  `datetime` DATETIME NOT NULL,
  `EPC` varchar(200) NOT NULL ,
  `ip` varchar(50) NOT NULL ,

  PRIMARY KEY  (ip, EPC, datetime),
  FOREIGN KEY (EPC) REFERENCES Product(EPC) ON DELETE CASCADE,
  FOREIGN KEY (ip) REFERENCES RFID_Reader(ip) ON DELETE CASCADE
);  

这是表格中的数据:

Track_Record (ip, longitude, lattitude, datetime, EPC)
VALUES
('000.111.222', '27.4667 S', '153.0333 E', '2014-11-05 18:56:46', '03.0000A89.00016F.000169DCD'),
('000.111.222', '27.4667 S', '153.0333 E', '2015-05-12 13:21:16', '03.0000A89.00016F.000169DCD'),
('555.666.777', '22.2783 N', '114.1747 E', '2012-07-19 12:22:16', '04.0000A89.00016F.000169DCD'),
('000.111.222', '27.4667 S', '153.0333 E', '2011-03-01 11:43:26', '03.0000A89.00016F.000169DCD'),
('555.666.777', '22.2783 N', '114.1747 E', '2014-09-02 18:53:14', '06.0000A89.00016F.000169DCD'),
('222.333.444', '59.3500 N', '18.0667 E', '2015-10-15 18:23:18', '04.0000A89.00016F.000169DCD'),
('333.444.555', '15.7833 S', '47.8667 W', '2015-02-22 19:53:16', '01.0000A89.00016F.000169DCD'),
('444.555.666', '51.5072 N', '0.1275 W', '2013-01-11 22:21:15', '04.0000A89.00016F.000169DCD');

如果有人知道我如何获得此信息,我将非常感谢您提供的任何帮助。

由于 科里

1 个答案:

答案 0 :(得分:3)

听起来你需要maxminepc之间的差异,所以这个:

select epc, max(`datetime`), min(`datetime`), timediff(max(`datetime`), min(`datetime`))
  from Track_Record
  order by timediff(max(`datetime`), min(`datetime`)) desc
  limit 1;

上述示例数据的结果:

+-----------------------------+---------------------+---------------------+--------------------------------------------+
| epc                         | max(`datetime`)     | min(`datetime`)     | timediff(max(`datetime`), min(`datetime`)) |
+-----------------------------+---------------------+---------------------+--------------------------------------------+
| 03.0000A89.00016F.000169DCD | 2015-10-15 18:23:18 | 2011-03-01 11:43:26 | 838:59:59                                  |
+-----------------------------+---------------------+---------------------+--------------------------------------------+
1 row in set, 1 warning (0.00 sec)