我的应用程序中有一个简单的 SQL 语句:
SELECT SQL_NO_CACHE key_event_id, MAX(report_ts) AS max_ts
FROM `key_event_reports`
WHERE report_model_id = 2
GROUP BY key_event_id;
该key_event_reports
表中等大小(~ 17M 行),这是表定义:
CREATE TABLE IF NOT EXISTS `key_event_reports` (
`key_event_report_id` int(20) NOT NULL AUTO_INCREMENT,
`report_model_id` int(5) NOT NULL,
`key_event_id` int(5) NOT NULL,
`title_id` int(15) NOT NULL,
`report_ts` datetime NOT NULL,
`report_time` time NOT NULL,
`total` int(7) NOT NULL DEFAULT '0',
`pos` int(7) NOT NULL DEFAULT '0',
`neg` int(7) NOT NULL DEFAULT '0',
`smooth_total` float NOT NULL DEFAULT '0',
`smooth_pos` float NOT NULL DEFAULT '0',
`smooth_neg` float NOT NULL DEFAULT '0',
`buzz` float NOT NULL DEFAULT '0',
`sentiment` float NOT NULL DEFAULT '0',
PRIMARY KEY (`key_event_report_id`),
UNIQUE KEY `key_event_id_4` (`key_event_id`,`report_model_id`,`title_id`,`report_ts`),
KEY `report_model_id` (`key_event_id`,`report_time`),
KEY `report_model_id_2` (`report_model_id`,`key_event_id`,`report_ts`),
KEY `key_event_id` (`key_event_id`,`report_model_id`,`report_time`,`title_id`,`smooth_total`),
KEY `key_event_id_3` (`key_event_id`,`report_model_id`,`report_time`,`title_id`,`smooth_pos`),
KEY `key_event_id_2` (`key_event_id`,`report_model_id`,`report_time`,`title_id`,`smooth_neg`),
KEY `get_latest_report` (`report_model_id`,`report_ts`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=16967636 ;
report_model_id 始终为 2(数据库中还没有其他模型,但这很快就会改变)并且每 10 分钟报告 10 个不同的 key_events。
此查询在没有缓存的情况下需要很长时间(大约 20 秒)。当上面的查询用作较大语句中的子查询时,问题会变得更糟:
SET @report_model_id = 2;
SET @message_id = ?;
SET @title_id = ?
SET @min_score = 5;
SET @min_message_id = (
SELECT MIN(message_id)
FROM `messages`
WHERE msg_time > DATE_SUB(NOW(), INTERVAL 20 MINUTE)
);
SELECT
ke.key_event_id AS key_event_id,
COALESCE(kermmid.message_id, MIN(mhke.message_id)) AS max_message_id,
ker_max.max_ts AS last_report_ts
FROM `key_events` ke
LEFT JOIN (
SELECT key_event_id, MAX(report_ts) AS max_ts
FROM `key_event_reports`
WHERE report_model_id = 2
GROUP BY key_event_id
) ker_max
ON ( ker_max.key_event_id = ke.key_event_id )
LEFT JOIN `key_event_reports` ker
ON (
ker.key_event_id = ke.key_event_id
AND ker.report_model_id = @report_model_id
AND ker.title_id = @title_id
AND ker.report_ts = @actcurrent
)
LEFT JOIN `key_event_report_max_message_ids` kermmid
ON (
kermmid.key_event_id = ker.key_event_id
AND kermmid.report_model_id = ker.report_model_id
AND kermmid.report_ts = ker.report_ts
)
LEFT JOIN `messages_has_key_events` mhke
ON (
mhke.key_event_id = ke.key_event_id
AND mhke.title_id = @title_id
AND mhke.message_id > @min_message_id
AND mhke.message_id < @message_id
AND mhke.score > @min_score
)
GROUP BY
ke.key_event_id;
如果我在其中使用子查询,执行时间也会从 ~50ms 变为 >20s。
这可能是什么原因,我怎么可能优化我的语句或数据库结构?