請你幫我優化這個查詢。我花了很多時間,並且仍然無法將其改寫成足夠快的速度(比如說運行在秒鐘之內,而不是現在的分鐘)。MySQL查詢優化
查詢:
SELECT m.my_id, m.my_value, m.my_timestamp
FROM (
SELECT my_id, MAX(my_timestamp) AS most_recent_timestamp
FROM my_table
WHERE my_timestamp < '2011-03-01 08:00:00'
GROUP BY my_id
) as tmp
LEFT OUTER JOIN my_table m
ON tmp.my_id = m.my_id AND tmp.most_recent_timestamp = m.my_timestamp
ORDER BY m.my_timestamp;
MY_TABLE定義如下:
CREATE TABLE my_table (
my_id INTEGER NOT NULL,
my_value VARCHAR(4000),
my_timestamp TIMESTAMP default CURRENT_TIMESTAMP NOT NULL,
INDEX MY_ID_IDX (my_id),
INDEX MY_TIMESTAMP_IDX (my_timestamp),
INDEX MY_ID_MY_TIMESTAMP_IDX (my_id, my_timestamp)
);
該查詢的目標是選擇最近的my_value
每個my_id
一些時間戳之前。 my_table
包含約1億個條目,並且需要大約8分鐘才能完成。
解釋:
+----+-------------+-------------+-------+------------------------------------------------+-------------------------+---------+---------------------------+-------+---------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------------+-------+------------------------------------------------+-------------------------+---------+---------------------------+-------+---------------------------------------+ | 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 90721 | Using temporary; Using filesort | | 1 | PRIMARY | m | ref | MY_ID_IDX,MY_TIMESTAMP_IDX,MY_ID_TIMESTAMP_IDX | MY_TIMESTAMP_IDX | 4 | tmp.most_recent_timestamp | 1 | Using where | | 2 | DERIVED | my_table | range | MY_TIMESTAMP_IDX | MY_ID_MY_TIMESTAMP_IDX | 8 | NULL | 61337 | Using where; Using index for group-by | +----+-------------+-------------+-------+------------------------------------------------+-----------------------+---------+---------------------------+------+---------------------------------------+
您確定這是您發佈的查詢的查詢計劃嗎?該計劃提到表「nv」,但查詢中沒有這樣的表。該查詢可能不是正確的,因爲子選擇中的my_id的值可能不是(實際上不可能是)my_timestamp = MAX(my_timestamp)所在行的id。 – outis 2011-03-02 14:26:49
哪個版本的mysql?以及爲什麼表名1被刪除。 – Zimbabao 2011-03-02 14:27:58
不應該將您的連接條件設爲'... AND tmp.most_recent_timestamp = m.my_timestamp ...'?內部查詢也看起來缺少一個「GROUP BY」。 – 2011-03-02 14:32:28