我知道这个主题很老,但如果我可以与您分享我的经验。也许这对下一个人有用:)
我有一张非常大的桌子,上面有我所有设备的温度(100+),我所有的设备每 5 秒推动一次温度(一个设备有 6 个视野区域,我可以得到每个区域的温度)。
所以桌子很大。对我来说,之前的响应对于大量数据来说效率不高。看看我在做什么:
这是我的大表的架构:
CREATE TABLE `histozone` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`camera_id` INT(11) NULL DEFAULT NULL,
`Date` DATE NOT NULL,
`Time` TIME NOT NULL,
`ZoneId` INT(11) NOT NULL,
`AverageTemperature` INT(11) NOT NULL,
`MinimumTemperature` INT(11) NOT NULL,
`MaximumTemperature` INT(11) NOT NULL,
PRIMARY KEY (`id`),
INDEX `IDX_19E8F664B47685CD` (`camera_id`),
INDEX `datetime` (`camera_id`, `Date`, `Time`),
);
如您所见,我对每一行都有Date
and 。Time
- 在我的 PHP 代码中使用 MEMORY 引擎为每个设备创建一个临时表。我将 tmp 表限制在一个持续时间(日期和时间)内。
DROP TEMPORARY TABLE IF EXISTS histoZoneMaxTempCamera{$cameraId};
CREATE TEMPORARY TABLE histoZoneMaxTempCamera{$cameraId} (
`id` INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
`originalid` INT(11) NOT NULL,
`date` DATE NOT NULL,
`time` TIME NOT NULL,
`zoneid` INT(11) NOT NULL,
`maximumtemperature` INT(11) NOT NULL,
INDEX (`maximumtemperature`)
) ENGINE=MEMORY;
INSERT INTO histoZoneMaxTempCamera{$cameraId} (`originalid`, `date`, `time`, `zoneid`, `maximumtemperature`)
SELECT
h.id,
h.Date,
h.Time,
h.ZoneId,
h.MaximumTemperature
FROM histozone h
INNER JOIN (
SELECT
hz.camera_id,
MAX(hz.MaximumTemperature) AS MaximumTemperature,
hz.Date,
hz.Time
FROM histozone hz
WHERE hz.camera_id = '{$cameraId}'
AND hz.Date >= '{$date}'
AND hz.Time >= '{$time}'
GROUP BY hz.Date, hz.Time
) histozoneMaxTemp
ON h.Date = histozoneMaxTemp.Date
AND h.Time = histozoneMaxTemp.Time
AND h.MaximumTemperature = histozoneMaxTemp.MaximumTemperature
WHERE h.camera_id = histozoneMaxTemp.camera_id
ORDER BY h.Date ASC, h.Time ASC;
- 最后一步是获取数据、趋势等……我,我只想要波动的温度点。在同一级别有很多点的图表并不有趣。
SELECT
a.*
FROM (
SELECT
x.id AS xid
, x.Date AS `Date`
, x.Time AS `Time`
, x.maximumtemperature AS maximumtemperature
, y.maximumtemperature AS previousmaximumtemperature
, x.maximumtemperature - y.maximumtemperature diff
,(x.maximumtemperature-y.maximumtemperature)/MAX(x.id) trend
FROM histoZoneMaxTempCamera{$cameraId} x
LEFT JOIN histoZoneMaxTempCamera{$cameraId} y
ON y.id = (x.id - 1)
GROUP BY x.id
) a
WHERE a.trend <> (
SELECT b.trend
FROM (
SELECT
x.id AS xid
,(x.maximumtemperature-y.maximumtemperature)/MAX(x.id) trend
FROM histoZoneMaxTempCamera{$cameraId} x
LEFT JOIN histoZoneMaxTempCamera{$cameraId} y
ON y.id = (x.id - 1)
GROUP BY x.id
) b
WHERE b.xid = a.xid - 1
) OR a.xid = 1
;
这非常有效,即使有一个非常大的起始表也非常快。