【发布时间】:2014-05-03 07:18:25
【问题描述】:
我有一个 MySQL 数据库,每 15 分钟记录一次数据。为简单起见,我们假设有 2 个字段:
DATETIME Created
Double Value
我想绘制一个图表,该图表需要每小时的开盘、最小值、最大值和收盘值。为此,我需要将 MySQL 查询的结果返回到我的 PHP 以创建 JSON。我想在 MySQL 查询中执行此操作,以便缓存响应。
这是一个问题示例,假设 9 个数据点试图获得 2 小时组:
Creation Value
2014-03-25 12:15:00 413.17011
2014-03-25 12:00:00 414
2014-03-25 11:45:00 415
2014-03-25 11:30:00 415
2014-03-25 11:15:00 415.5
2014-03-25 11:00:00 415.5
2014-03-25 10:45:00 416
2014-03-25 10:30:00 416
2014-03-25 10:15:00 415.99
我需要:
Hour 1 (11:15:00 to 12:15:00)
Open: 415.5
Close: 413.17011
High: 415.5
Low: 413.17011
Hour 2 (10:15:00 to 11:15:00)
Open: 415.99
Close: 415.5
High: 416
Low: 415.5
当然,这需要在整个 24 小时内重复,这只是一个示例。 非常感谢任何帮助!
这里是示例的当前 MySQL 转储(使用 MySQL 版本 2.6.4-pl3):
--
-- Table structure for table `exampleTable`
--
CREATE TABLE `exampleTable` (
`created` datetime NOT NULL,
`value` double NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
--
-- Dumping data for table `exampleTable`
--
INSERT INTO `exampleTable` VALUES ('2014-03-25 12:15:00', 413.17011);
INSERT INTO `exampleTable` VALUES ('2014-03-25 12:00:00', 414);
INSERT INTO `exampleTable` VALUES ('2014-03-25 11:45:00', 415);
INSERT INTO `exampleTable` VALUES ('2014-03-25 11:30:00', 415);
INSERT INTO `exampleTable` VALUES ('2014-03-25 11:15:00', 415.5);
INSERT INTO `exampleTable` VALUES ('2014-03-25 11:00:00', 415.5);
INSERT INTO `exampleTable` VALUES ('2014-03-25 10:45:00', 416);
INSERT INTO `exampleTable` VALUES ('2014-03-25 10:30:00', 416);
INSERT INTO `exampleTable` VALUES ('2014-03-25 10:15:00', 415.99);
【问题讨论】:
-
没有回复让我很担心,所以我会尽可能缩短这个问题。
-
正如提示:如果可以,您可能希望将日期和时间分成两列(类型为
date和time)。这样您就不需要每次都将DATE()投射到created上,而是可以使用新的日期列。然后,您也可以向该列添加索引,从而加快查询速度。 See this sqlfiddle for an example. -
更好:combined index on both new columns。避免两个文件排序。