假設我有一個簡單的表user_id
(INT),date
(DATE)和earnings
(FLOAT)。我正在試圖決定如何索引這張表。一列,兩列或兩者的索引?
目前,我的PRIMARY鍵設置爲user_id
,date
。
但並非所有查詢都使用此密鑰。我在下面粘貼了一些示例查詢。所有這些都經常運行。
SELECT SUM(earnings) FROM stats WHERE user_id=? //Get total earnings
SELECT SUM(earnings) FROM stats WHERE user_id=? AND date between ? AND ? //Get earnings for date range
SELECT user_id FROM stats WHERE date=$today ORDER BY earnings DESC LIMIT 0,5 //Get todays highest earners
SELECT user_id FROM stats WHERE date>$month ORDER BY earnings DESC LIMIT 0,5 //Get months highest earners
正如你所看到的,上面兩個查詢使用索引很好,但後兩個沒有。
我正在考慮在date
,earnings
上創建一個索引,但由於date
已經在索引中,所以感覺很奇怪。這是正確的解決方案嗎?
如果不是,索引此表的最佳方法是什麼?
user_id和date必須一起保留至少一個唯一索引。感謝你的回答! – hellohellosharp 2013-03-24 01:04:55