我刚刚创建了一个表:
CREATE TABLE `table_test` (
`time` date NOT NULL,
`line_id` char(36) NOT NULL,
`location_id` char(36) NOT NULL,
`placement_id` char(36) NOT NULL,
`flight_id` char(36) NOT NULL,
`impressions` int(11) DEFAULT `0`,
PRIMARY KEY (`time`,`line_id`,`location_id`,`placement_id`,`flight_id`),
KEY `table_test_IDX` (`time`,`placement_id`,`line_id`,`impressions`) USING
BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8
然后,当我尝试执行查询时:
SELECT
time,
placement_id,
line_id,
SUM(impressions) AS totalImpress
FROM
table_test
WHERE
time BETWEEN '2017-11-01' AND '2017-11-30'
GROUP BY time , placement_id , line_id;
只花了0.28秒。
但当我试图执行时:
SELECT
daily.`time`,
daily.placement_id,
daily.line_id,
daily.totalImpress
FROM
(SELECT
time,
placement_id,
line_id,
SUM(impressions) AS totalImpress
FROM
table_test
WHERE
time BETWEEN '2017-11-01' AND '2017-11-30'
GROUP BY time , placement_id , line_id)
daily
执行起来花了7秒多。
我做错什么了?
非常感谢。
1条答案
按热度按时间niwlg2el1#
执行时间并不总是效率的最佳衡量标准(奇怪,我知道。)mysql允许查询缓存。这基本上意味着,如果重复运行同一个查询,那么在后续运行时,查询速度会明显加快。如果您想优化您的查询,我建议在查询的开头使用“explain”命令。