這個查詢是非常簡單的,所有我想做的事,就是讓所有在給定的類別由last_updated
字段排序的文章:如何避免在多對多查詢中使用「臨時」?
SELECT
`articles`.*
FROM
`articles`,
`articles_to_categories`
WHERE
`articles`.`id` = `articles_to_categories`.`article_id`
AND `articles_to_categories`.`category_id` = 1
ORDER BY `articles`.`last_updated` DESC
LIMIT 0, 20;
但它運行很慢。這裏解釋什麼說:
select_type table type possible_keys key key_len ref rows Extra
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
SIMPLE articles_to_categories ref article_id,category_id article_id 5 const 5016 Using where; Using temporary; Using filesort
SIMPLE articles eq_ref PRIMARY PRIMARY 4 articles_to_categories.article_id 1
有沒有辦法重寫此查詢或添加額外的邏輯來我的PHP腳本,以避免Using temporary; Using filesort
和速度的東西呢?
表結構:
*articles*
id | title | content | last_updated
*articles_to_categories*
article_id | category_id
UPDATE
我已經last_updated
索引。我想我的情況在d ocumentation解釋說:
在某些情況下,MySQL不能使用 索引來解決ORDER BY, 儘管它仍然使用索引來找到 WHERE子句匹配的行。 這些情況包括:
用於提取行的鍵不同於ORDER BY中使用的鍵: SELECT * FROM t1 WHERE key2 =常量ORDER BY key1;
要加入很多表,並在ORDER BY的 列不是從第一個非恆定表 用於檢索所有行 。 (這是EXPLAIN輸出 第一表 沒有一個const連接類型。)
,但我仍然不知道如何解決這個問題。
速度有多慢?你使用了什麼引擎? – 2011-03-29 13:29:47
@ f00查詢運行3-5秒,我正在使用innodb(可以在標籤中看到) – 2011-03-29 13:51:51
也許檢查我的例子 - 這是重要的聚類PK的順序。 – 2011-03-29 13:57:12