2013-05-15 177 views
0

我應該如何優化這個查詢?優化mysql查詢語句

EXPLAIN EXTENDED SELECT 
    cm . *, 
    u1.Firstname AS u1Firstname, 
    u1.Lastname AS u1Lastname, 
    u2.Firstname AS u2Firstname, 
    u2.Lastname AS u2Lastname, 
    COUNT(*) AS Count 
FROM 
    ChatMessage AS cm 
     LEFT JOIN 
    Users AS u1 ON cm.UserId = u1.UserId 
     LEFT JOIN 
    Users AS u2 ON cm.FriendId = u2.UserId 
WHERE 
    (cm.UserId IN (292 , 289)) AND (cm.FriendId IN (292 , 289)) 
ORDER BY cm.DateAdded DESC; 

說明:

1 SIMPLE釐米ALL fk_ChatMessage_Users1,fk_ChatMessage_Users2 238 59.24使用其中
1 SIMPLE U1 eq_ref PRIMARY PRIMARY 4 mhware.cm.UserId 1 100.00
1 SIMPLE U2 eq_ref小學一年級4 mhware.cm.FriendId 1 100.00

問題是:ChatMessa ge正在使用外鍵,一個在UserId上,一個在FriendId上,指向User Table中的UserId。

在EXPLAIN上,您可以看到它不知道如何正確使用索引。如果即時添加(UserId,FriendId)或/和(FriendId,UserId)的新索引,它有4種可能性,並且不使用它們中的任何一種。

本聲明運行時間約爲1秒鐘,並將我的慢查詢日誌文件轉儲爲垃圾。

謝謝。

回答

0

你可以嘗試添加2個索引。一個在cm.UserID上,另一個在cm.FriendId上?我不太瞭解你的外鍵,因爲你正在使用左連接,所以你說用戶可能不存在?爲什麼要使用外鍵?

0

嘗試(用戶ID,FriendId)增加一個新的指數,用下面的查詢:

SELECT 
    cm . *, 
    u1.Firstname AS u1Firstname, 
    u1.Lastname AS u1Lastname, 
    u2.Firstname AS u2Firstname, 
    u2.Lastname AS u2Lastname, 
    COUNT(*) AS Count 
FROM (select 289 u, 289 f union all 
     select 289, 292 union all 
     select 292, 289 union all 
     select 292, 292) uf 
JOIN ChatMessage AS cm ON uf.u = cm.UserId and uf.f = cm.FriendId 
LEFT JOIN Users AS u1 ON cm.UserId = u1.UserId 
LEFT JOIN Users AS u2 ON cm.FriendId = u2.UserId 
ORDER BY cm.DateAdded DESC;