0
我想問下如何能夠優化這個查詢更快的速度。無論如何,它對很多行都很慢。同樣三張表的索引仍然無法快速搜索非常大的表格。請,我非常感謝任何意見,改進。謝謝。非常緩慢的查詢大表(含兩個左連接的表)
SET @timeset := 0;
SET @timeset2 := 0;
SET @previousDay := 0;
SET @previousDay2 := 0;
SET @datefrom = cast('2017-05-01 00:00:00' as datetime);
SET @dateto = cast('2017-05-15 00:00:00' as datetime);
SET @rownumFirstTable := 0;
SET @rownumSecondTable = 0;
SELECT
`hour_time_local`,
DAY(`hour_time_local`) AS `day`,
IF(DAY(`hour_time_local`) != @previousDay, @timeset:=0, @timeset:=1) AS ``,
@rownumFirstTable := IF(@timeset != 0, @rownumFirstTable :[email protected] +1, @rownumFirstTable :=1) AS `row_first_table`,
@previousDay := DAY(`hour_time_local`),
`low_speed` AS `LOW_SPEED_15_PERCENTILE`,
`day_second_table`,
`LOW_SPEED_15_PERCENTILE_INDEX`,
`row_second_table`,
`high_speed`,
`hour_time_second_table`,
`day_second_table`,
`HIGH_SPEED_15_PERCENTILE_INDEX`
FROM
t.table_speed AS `first_table`
LEFT JOIN
(
SELECT
COUNT(low_speed) AS `count_low_speed`,
CEIL((15/100) * COUNT(low_speed)) AS `LOW_SPEED_15_PERCENTILE_INDEX`,
CEIL((15/100) * COUNT(high_speed)) AS `HIGH_SPEED_15_PERCENTILE_INDEX`,
DAY(`hour_time_local`) AS `day_second_table`
FROM t.table_speed
WHERE (`hour_time_local` >= @datefrom) AND (`hour_time_local` < @dateto) AND (`traffic_id` = 'XXXXXXXX')
GROUP BY DAY(`hour_time_local`), MONTH(`hour_time_local`), YEAR(`hour_time_local`)
) AS `second_table` ON `id` = `first_table`.`id`
LEFT JOIN
(
SELECT
DAY(`hour_time_local`) AS `day_second_table`,
@timeset2 AS `timeset`,
IF(DAY(`hour_time_local`) != @previousDay2, @timeset2:=0, @timeset2:=1) AS ``,
@previousDay2 := DAY(`hour_time_local`),
IF(@timeset2 != 0, @rownumSecondTable:[email protected]+1, @rownumSecondTable:=1),
@rownumSecondTableAS `row_second_table`,
`hour_time_local` AS `hour_time_second_table`,
`ht_high_speed` AS `high_speed`
FROM t.table_speed, (SELECT @rownumSecondTableAS :=0) AS `third_table`
WHERE (`hour_time_local` >= @datefrom) AND (`hour_time_local` < @dateto) AND (`traffic_id` = '703170016-1') AND (`ht_high_speed` > 0)
) AS `third_table` ON `id` = `first_table`.`id`
WHERE (`hour_time_local` >= @datefrom) AND (`hour_time_local` < @dateto) AND (`traffic_id` = '703170016-1') AND (`low_speed` > 0)
HAVING
(
(
(`day` = `day_first_table`) AND (`day` = `day_second_table`) AND ((`row_first_table` = `LOW_SPEED_15_PERCENTILE_INDEX`) AND (`row_second_table` = `HIGH_SPEED_15_PERCENTILE_INDEX`))
)
)
ORDER BY `hour_time_local` ASC;
哪個版本的MySQL?較新的版本可以爲這些派生表自動創建索引;舊版本的速度很慢。請提供'EXPLAIN SELECT ...'和'SHOW CREATE TABLE'。 –