我刚创建了一个表格:
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秒。
我在这里做错了什么?
非常感谢。
答案 0 :(得分:0)
执行时间并不总是效率的最佳指标。 (很奇怪,我知道。)MySQL允许查询缓存。这基本上意味着如果您重复运行相同的查询,它在后续运行中会明显加快。如果您想优化查询,我建议使用" EXPLAIN"在查询开头的命令。