【发布时间】:2012-01-08 13:34:55
【问题描述】:
我有三个表,我需要根据一个公共字段连接它们的数据。
示例伪表定义:
barometer_log(设备、压力浮动、采样时间时间戳)
温度日志(设备整数、温度浮点数、采样时间时间戳)
magnitude_log(设备整数、幅度浮点、utcTime 时间戳)
每个表最终将包含数十亿行,但目前每个表包含大约 500,000 行。
我需要能够将表中的数据(FULL JOIN)组合起来,以便将 sampleTime 合并为一列(COALESE),从而为我提供如下行: 设备、采样时间、压力、温度、幅度
我需要能够通过指定设备以及开始和结束日期来查询数据,例如 选择 .... 其中 device=1000 和 sampleTime 在 '2011-10-11' 和 '2011-10-17' 之间
我尝试了使用 RIGHT 和 LEFT 连接的不同 UNION ALL 技术 正如MySql full join (union) and ordering on multiple date columns 和MySql full join (union) and ordering on multiple date columns 中所建议的那样,但是查询花费的时间太长,我必须停止它或在运行几个小时后抛出有关临时文件大小的错误。 对我来说,查询这三个表并在可接受的时间范围内合并它们的输出的最佳方法是什么?
这是建议的完整表定义。 注意:未包含设备表。
magnitude_log
CREATE TABLE magnitude_log (
device int(11) NOT NULL,
magnitude float not NULL,
sampleTime timestamp NOT NULL,
PRIMARY KEY (device,sampleTime),
CONSTRAINT magnitudeLog_device
FOREIGN KEY (device)
REFERENCES device (id)
ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
气压计日志
CREATE TABLE barometer_log (
device int(11) NOT NULL,
pressure float not NULL,
sampleTime timestamp NOT NULL,
PRIMARY KEY (device,sampleTime),
CONSTRAINT barometerLog_device
FOREIGN KEY (device)
REFERENCES device (id)
ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
温度日志
CREATE TABLE temperature_log (
device int(11) NOT NULL,
sampleTime timestamp NOT NULL,
temperature float default NULL,
PRIMARY KEY (device,sampleTime),
CONSTRAINT temperatureLog_device
FOREIGN KEY (device)
REFERENCES device (id)
ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
【问题讨论】:
-
你在
device列上有索引吗(我猜你用它来连接)? -
我在设备上有复合索引,在所有三个表上都有 sampleTime
-
请添加表格定义。
device是主键还是唯一键?还是(device, sampleTime)是每张桌子的PK? -
(device, sampleTime) 在每个表中都是 pk。 device 也是一个 fk
-
好的,现在,我猜你想在
(device, sampleTime)组合上使用FULL JOIN。
标签: mysql join union union-all