假设我有一个简单的表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