2011-03-08 66 views
0

UPDATE:補充說,運行查詢第二最:從這個查詢的MySQL索引中受益?

(考慮採取索引的時候,也許需要???)

SELECT m.time, m.message, m.receiver_uid AS receiver, m.sender_uid AS sender 
    FROM messages AS m, users AS u 
    WHERE u.uid = '$coID' 
     AND ((m.receiver_uid = '$meID' AND m.sender_uid = '$coID') OR 
       (m.receiver_uid = '$coID' AND m.sender_uid = '$meID')) 
    ORDER BY m.time DESC 
  • $ MEID是用戶的ID,誰運行wuery,
  • $ coID是聯繫人的ID。

我有一個大一些查詢,並將其每次運行一個用戶訪問我的網頁。

SELECT m2.message, m2.time, m2.sender_uid AS sender, m2.receiver_uid AS receiver, 
     m.contact, u.ufirstname 
FROM ( SELECT CASE 
       WHEN sender_uid = '$me' THEN receiver_uid 
       ELSE sender_uid 
       END AS contact, 
       MAX(time) AS maxtime 
     FROM messages 
     WHERE sender_uid = '$me' OR receiver_uid = '$me' 
     GROUP BY CASE 
       WHEN sender_uid = '$me' THEN receiver_uid 
       ELSE sender_uid 
       END          ) AS m 
INNER JOIN messages m2 ON m.maxtime = m2.time 
AND ((m2.sender_uid = '$me' AND m2.receiver_uid = m.Contact) 
OR (m2.receiver_uid = '$me' AND m2.sender_uid = m.Contact)) 
INNER JOIN users AS u ON m.contact = u.uid 
ORDER BY time DESC 
  • $我是誰運行查詢的用戶的ID

這個查詢(成功)檢索:

LAST MESSAGE from EVERY 'CONVERSATION' ordered by TIME. 

所以它會得到的最後消息(在每個PM會話中是否發送或接收消息) 然後按時間排序並檢索聯繫人信息。

請告訴我,如果我沒有正確解釋它。

我的MySQL表看起來是這樣的:從什麼指數(ES)將這個查詢利益

receiver_id | sender_id | message | time 

(用戶表已有的ID的主鍵,以便在加入部分檢索聯繫人的名稱應該是有效的)

EXPLAIN輸出:

大查詢:

id select_type  table type possible_keys key  key_len  ref  rows Extra 
1 PRIMARY  <derived2> ALL  NULL NULL NULL NULL 4 Using temporary; Using filesort 
1 PRIMARY  m2 ALL  NULL NULL NULL NULL 42 Using where 
1 PRIMARY  u eq_ref PRIMARY  PRIMARY  4 m.contact 1 Using where 
2 DERIVED  messages ALL  NULL NULL NULL NULL 42 Using where; Using temporary; Using filesort 

在更新部分查詢:

id select_type  table type possible_keys key  key_len  ref  rows Extra 
1 SIMPLE u const PRIMARY  PRIMARY  4 const 1 Using index; Using filesort 
1 SIMPLE m ALL  NULL NULL NULL NULL 42 Using where 

回答

0

我發現通過跟蹤和錯誤,索引時間減少了加載時間。 所以這可能是我的問題的答案。

0

隨着消息表的增長,此查詢將開始變得越來越慢。根據用戶參與的對話數量,您將開始看到呈指數衰減的性能。儘管messages.time,messages.sender_uid和messages.receiver_uid上的單獨索引目前會有所幫助,但是除非您修改了郵件表,否則索引將從長遠角度幫助您。特別是當你有超過幾十萬條消息。

我建議維護一個關聯類型類型,將用戶鏈接到對話和他們的最後一個消息ID。東西看起來像:

user_id | conversation_id | message_id

然後查找此表,而不是執行復雜且昂貴的查詢。這大大減少了您在消息表上需要執行的掃描次數。雖然它稍微增加了複雜性,但性能不會像上面的查詢那樣降級。

+0

如何將舊的(14天)消息移動到較舊的表中? 所以,只有當用戶真的想閱讀舊信息時,他必須在長表中搜索。 – SuperSpy 2011-03-08 11:25:44