2010-09-01 52 views
1

從MySQL文檔中的排序優化,我引用...當GROUP BY和ORDER BY表達式不同時優化SQL查詢?

在某些情況下,MySQL不能使用 索引來解決ORDER BY, 儘管它仍然使用索引來找到 匹配的行WHERE子句。 這些情況包括:

  • 您有不同的ORDER BY和GROUP BY表達式。

是否有任何補救解決方法呢?

我查詢...

SELECT * 
FROM (`product`) 
WHERE `Category1` = 'PC' 
AND `Category2` = 'desktop' 
GROUP BY `product_code` 
ORDER BY `reviews` desc, `popularity` desc 
LIMIT 10 

Explain輸出...

select_type: SIMPLE 
table: product 
type: ref 
possible_keys: Category1_idx 
key: Category1_idx 
key_len: 390 
ref: const, const 
rows: 508 
Extra: Using where; Using temporary 

問候

回答

1

GROUP BY通常與像SUM函數(),以總記錄中使用。您的查詢似乎不需要group by子句。以下工作會更好嗎?

SELECT * FROM(product) WHERE Category1 = 'PC' 和Category2 = '桌面' ORDER BY product_codereviews遞減,popularity遞減 LIMIT 10

您可以創建一個索引來匹配課程。

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

+0

我需要GROUP BY來緩解一些編程操作。除了刪除GROUP BY之外是否還有其他方法 - 可能是一些子查詢或其他內容? – vikmalhotra 2010-09-01 10:14:27

+0

您是否檢查過現有查詢正在返回的記錄,如果您沒有進行彙總分組,有時結果可能會出現意外。 – Jaydee 2010-09-01 10:50:19