我有以下表格:
CREATE TABLE `data` (
`date_time` decimal(26,6) NOT NULL,
`channel_id` mediumint(8) unsigned NOT NULL,
`value` varchar(40) DEFAULT NULL,
`status` tinyint(3) unsigned DEFAULT NULL,
`connected` tinyint(1) unsigned NOT NULL,
PRIMARY KEY (`channel_id`,`date_time`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
CREATE TABLE `channels` (
`channel_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`channel_name` varchar(40) NOT NULL,
PRIMARY KEY (`channel_id`),
UNIQUE KEY `channel_name` (`channel_name`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
我想知道是否有人可以就如何优化或重写以下查询给我一些建议:
SELECT channel_name, t0.date_time, t0.value, t0.status, t0.connected, t1.date_time, t1.value, t1.status, t1.connected FROM channels,
(SELECT MAX(date_time) AS date_time, channel_id, value, status, connected FROM data
WHERE date_time <= 1300818330
GROUP BY channel_id) AS t0
RIGHT JOIN
(SELECT MAX(date_time) AS date_time, channel_id, value, status, connected FROM data
WHERE date_time <= 1300818334
GROUP BY channel_id) AS t1
ON t0.channel_id = t1.channel_id
WHERE channels.channel_id = t1.channel_id
基本上,我在两个不同的时间获取每个 channel_name 的值、状态和连接字段。由于 t0 始终 <= t1,因此字段可能存在于 t1 中,但不存在于 t0 中,我希望将其显示出来。这就是我使用 RIGHT JOIN 的原因。如果 t1 不存在,则 t0 也不存在,因此不应返回任何行。
问题似乎是因为我加入了子查询,所以没有索引可以使用?我尝试重写它以首先对数据表的 channel_id 进行自连接,但那是数百万行。
当 t0.value = t1.value & t0.status = t1.status & t0.connected = t1.connected 时,如果能够为每个最终行添加一个布尔字段,这也是很好的。
非常感谢您的宝贵时间。