2017-03-27 62 views
0

我在嘗試將索引添加到以下查詢中。MySQL - 我如何知道使用哪些索引?

SELECT * FROM Messages t WHERE perspective_user=? and timestamp BETWEEN ? AND ? AND 
timestamp_added = 
(select max(timestamp_added) from Messages t2 
where 
t2.author = t.author AND 
t2.body = t.body AND 
t2.timestamp = t.timestamp AND 
t2.timestamp_added <= ? 
) AND convo_id IN(SELECT convo_id FROM Conversations WHERE perspective_user=? AND identity=? AND timestamp_added=?); 

我首先想到的是三個指標:一是對perspective_user,時間戳,timestamp_added和convo_id,對作者,身體,時間戳和timestamp_added第二指標,以及perspective_user,身份和timestamp_added最終的指數。然而,這不起作用,並且據我所知,執行時間相同。

如何在此查詢中添加索引,更一般地說,我如何知道如何在將來正確添加索引?

+0

用'explain select ...'單獨執行查詢以查看它是如何執行的 –

+0

您將索引添加到表中而不是查詢 – efekctive

+0

這不是問題的一部分http://stackoverflow.com/questions/43023274/mysql-fig-out-what-indexes-to-use-and-not-working-as-expected?我已經解決了那裏的索引問題。 –

回答

0

要使用的索引?

  1. 索引取決於您的需求查詢。
  2. 大部分使用的索引都來自where子句。
  3. 索引使用的一個最好的事情是您的主鍵。
  4. 避免創建多個索引到您的表中,因爲它可能會使您的數據變慢查詢。

有關更多詳細信息,請參閱此indexes tutorial

相關問題